Why should there be generic?

Motivation generics are: 
a number of reasons contributed to the emergence of generics, and one of the reasons most interesting, is to create a container class.

Containers should be considered as one of the library's most reusability. First look at how the container class in the case of a no generic definition:

public class Container {
    private String key;
    private String value;

    public Container(String k, String v) {
        key = k;
        value = v;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

Container class holds a pair of key-value key-value pairs, but the type is set to die, also said that a key-value pair is a String-Integer type, this current Container can not do that if I want to create, you must then customize. So this is obviously very low reusability.

Of course, I can use Object instead of String, and before Java SE5, we can only do that because Object is the base class for all types, so you can direct the transition. But such flexibility is not enough, or because the specified type, but this time only the specified type of higher level, there may not specify the type? Is it possible to know at runtime what specific type?

So, there have been generic.

public class Container<K, V> {
    private K key;
    private V value;

    public Container(K k, V v) {
        key = k;
        value = v;
    }

    public K getKey() {
        return key;
    }

    public void setKey(K key) {
        this.key = key;
    }

    public V getValue() {
        return value;
    }

    public void setValue(V value) {
        this.value = value;
    }
}

At compile time, K and V is impossible to know specifically what type only at runtime will actually be constructed and allocate memory depending on the type. Container class can now look at the situation for different types of support:

public class Main {

    public static void main(String[] args) {
       Container<String, String> c1 = new Container<String, String>("电影名", "天下无贼");
        Container<String, Integer> c2 = new Container<String, Integer>("票房", 3);
        Container<Double, Double> c3 = new Container<Double, Double>(2.2, 2.2);
        System.out.println(c1.getKey() + " : " + c1.getValue());
        System.out.println(c2.getKey() + " : " + c2.getValue());
        System.out.println(c3.getKey() + " : " + c3.getValue());
    }
}

Related Links:

         https://segmentfault.com/a/1190000002646193 

         https://www.cnblogs.com/lwbqqyumidi/p/3837629.html

Guess you like

Origin www.cnblogs.com/inbeijing/p/11647015.html