Home Java javaTutorial Sharing multiple java generic examples

Sharing multiple java generic examples

Jan 18, 2017 am 11:00 AM

1. Generic class

1.1 Ordinary generic

package test.lujianing;
/**
 * 泛型类
 * @param <T>
 */
class Test<T>{
    private T obj;
    public void setValue(T obj){
        this.obj =obj;
    }
    public T getValue(){
        System.out.println(obj.getClass().getName());
        return obj;
    }
}
/**
 * 测试泛型类
 */
public class TestOne {
    public static void main(String[] args) {
        //测试Integer泛型
        Test<Integer> t1 = new Test<Integer>();
        t1.setValue(5);
        Integer i = t1.getValue();
        System.out.println(i);
        //测试Double泛型
        Test<Double> t2 = new Test<Double>();
        t2.setValue(5.55D);
        Double d = t2.getValue();
        System.out.println(d);
        //测试String泛型
        Test<String> t3 = new Test<String>();
        t3.setValue("hello world");
        String str =t3.getValue();
        System.out.println(str);
    }
}
Copy after login

Output result:

java.lang.Integer
5
java.lang.Double
5.55
java.lang.String
hello world
Copy after login

1.2 K/V generic

package test.lujianing;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by Administrator on 14-3-30.
 */
class TestKV<K,V>{
    private Map<K,V> map=new HashMap<K, V>();
    public void put(K k, V v) {
        map.put(k,v);
    }
    public V get(K k) {
        return map.get(k);
    }
}
public class TestFour{
    public static void main(String[] args) {
        TestKV<String,String> t = new TestKV<String, String>();
        t.put("name","jianing");
        System.out.println(t.get("name"));
        TestKV<String,Integer> t2 = new TestKV<String, Integer>();
        t2.put("age",24);
        System.out.println(t2.get("age"));
    }
}
Copy after login

Output result :

jianing
24
Copy after login

2. Generic interface

package test.lujianing;
/**
 * 泛型接口
 * @param <T>
 */
public interface TestImpl<T> {
    public void setValue(T t);
    public T getValue();
}
Copy after login

Output result:

1
hello word
Copy after login

3. Generic method

package test.lujianing;
/**
 * 泛型方法类
 */
class TestMethod{
    /**
     * 泛型方法
     */
    public <T>T getValue(Object s,Class<T> clazz) {
        System.out.println(clazz.getName());
        T t =null;
        if(clazz.getName().equals("java.lang.Integer")){
            Double d = Double.parseDouble(s.toString());
            int i =d.intValue();
            t=(T)new Integer(i);
        }
        if(clazz.getName().equals("java.lang.Double")){
            t=(T)new Double(s.toString());
        }
        return t;
    }
}
/**
 * 泛型方法测试类
 */
public class TestThree {
    public static void main(String[] args) {
        TestMethod t = new TestMethod();
        int i =t.getValue("30.0011",Integer.class);
        System.out.println(i);
        double d  =t.getValue("40.0022",Double.class);
        System.out.println(d);
    }
}
Copy after login

Output result:

java.lang.Integer
30
java.lang.Double
40.0022
Copy after login

4. Restrict generics

In the above example, there is no restriction on the scope of class Test type holder T, and the default limited type is equivalent to Object. For example, we want to limit T to a digital interface type. Just do this: class Test. In this way, the generic T in the class can only be the implementation class of the Number interface. If a non-Number interface is passed in, a compilation error will occur.

5. Wildcard generics

package test.lujianing;
import java.util.HashMap;
import java.util.Map;
/**
 * 通配泛型
 */
public class TestFive {
    public static void main(String[] args) {
        Map<String,Class<? extends Number>> map = new HashMap<String,Class<? extends Number>>();
        map.put("Integer",Integer.class);
        map.put("Double",Double.class);

        for (Map.Entry<String,Class<? extends Number>> entry : map.entrySet()) {
            System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());
        }
    }
}
Copy after login

Output results:

key:Double value:class java.lang.Double
key:Integer value:class java.lang.Integer
Copy after login

Simple example: example for 1.1

public static void main(String[] args) {
        //测试Integer泛型
        Test<Integer> t1 = new Test<Integer>();
        t1.setValue(5);
        fun(t1);
        //测试Double泛型
        Test<Double> t2 = new Test<Double>();
        t2.setValue(5.55D);
        fun(t2);
    }
    public static void fun(Test<?> t){
        System.out.println("通配泛型"+t.getValue());
    }
Copy after login

Output results:

java.lang.Integer
通配泛型5
java.lang.Double
通配泛型5.55
Copy after login

6. Supplement

In generics, you may encounter , etc. T and E are the first letters of Type and Element respectively. E is generally used to represent the type of elements in a collection type, such as the definition of the List interface, public interface List extends Collection. This is just a naming convention, there is no essential difference between the two.

For more java generic examples and related articles, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1654
14
PHP Tutorial
1252
29
C# Tutorial
1225
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles