java generics wildcards [T] and [?] concept entry

The purpose is to use the generic Java compiler mechanism to help us detect the code does not regulate the procedure could lead to the wrong code during compilation. For example, we all know that List container can hold any type of data, so we can put other types of String and Integer List simultaneously into the same container, but this practice is extremely dangerous. In a generic mechanism, this operation will cause the compiler does not pass, you will be mandatory data type List container modified to unify the type. This mechanism can help us reduce running hidden Bug.

Generic {T}

Generic widely used in the code.

Generic Usage

The generic position of use, i.e. the use of the class (Class), attributes (Field) and a method (Method) different locations, can be summarized as the use of generic following:

1. generic class. Generic identification added after the class name (<T ...>), one type of such holders for FIG.

2. Generic properties. Property must be combined with the generic use of the generic class, for receiving a generic class type held T.

3. generic method. Generic declaration (<T extends parent class name>) before the return value of the method, which is a generic parameter T defined in the method.

Supplement usage of generics

1. If the generic extends T is not modified (including classes and methods), which we call a generic unbounded; extend if modified, we call generic bounded.

2. If generic T, and the method returns no generic method parameters before the T type, which is not generic method, but the generic class.

3. Examples of objects independent generic method used (i.e., the method is a tool), and the class in the class tool.

4. generates an alarm when a generic T of the same name in the generic method generic T and class time, because the compiler sure which holds the object you want to use.

Bounded generic

Compared to the use of generic unbounded (type not defined), we can use the generic bounded (<T extends parent class name>) to define the scope of the object held by, or passing a generic method parameter range of the method, in order to ensure proper execution of business logic.

Bounded generic only the upper bound (extends), without the use of lower bound (relative to the wild card [?]).

Generics Inheritance

Generic description inherited by using a piece of code.

ArrayList<String> arrayList = new ArrayList<>();
Object object = new Object();
arrayList.add(object); // 编译器报错

Because ArrayList <String> instead of ArrayList <Object> sub-class, the compiler will complain, the error message is The method add (String) in the type ArrayList <String> is not applicable for the arguments (Object).

Tsuhaifu [?]

Wildcard is representative of an unknown type, used in the process (note the difference with the generic method, which does not require prior to the return type of the method declaration.

Upper bound wildcard

Wild upper bound upper bound that is defined wildcard statement with the keyword extends.

public static void process(List<? extends Foo> list){/ * ... * /}

Unbounded wildcard

Unbounded wildcard which does not limit the boundaries of a wildcard, does not require any modification to the keyword [?].

public static void printList(List<?> list){/*........*/}

Wildcards and functional form of declaration of type Object is a difference.

public static void printList(List<Object> list){/*........*/}

List <Object> and List <?> Is not the same, the former can be inserted Object Object or any subclass object, but the latter only in the case can be inserted null type mismatch.

public class TestWildCard {
    public void printList(List<String> list) {
        for (Object elem : list)
            System.out.print(elem + " ");
        System.out.println();
    }

    public void printList2(List<?> list) {
        for (Object elem : list)
            System.out.print(elem + " ");
        System.out.println();
    }

    public static void main(String[] args) {
        TestWildCard testWildcard = new TestWildCard();

        ArrayList<? extends Object> arrayList = new ArrayList<>();
        arrayList.add(null);
        // arrayList.add(testWildcard); // 报错

        ArrayList<Object> arrayList2 = new ArrayList<>();
        arrayList2.add(null);
        arrayList2.add("2");

        List<Integer> li = Arrays.asList(1, 2, 3);
        testWildcard.printList2(li);
        // testWildcard.printList(li); // 报错

        List<String> ls = Arrays.asList("one", "two", "three");
        testWildcard.printList2(ls);
        testWildcard.printList(ls);
    }
}

Lower bound wildcard

Lower bound wildcard wildcard that is defined under the super industry, declared with the keyword extends.

public static void addNumbers(List<? super Integer> list){}

Generic {T} wildcard [?] Difference

The most fundamental difference is that generics and wildcards Java compiler will infer generic {T} into specific types, and the wildcard [?] To infer an unknown type. Java editor can only operate specific types of unknown type can not be operated if there are to make changes to the operating parameters it is necessary to use generics, if only to see it can use wildcards.

In this way, we can design a secure interface to use wildcard feature. Defines such a method in the wild parameter interface, all the methods of the interface can modify the process parameters are transmitted over the succession.

interface GInterface {
    <T> void foo(List<? extends T> list);
}

public class GInterfaceImpl implements GInterface{
    @Override
    public <T> void foo(List<? extends T> list) {
        // 只能遍历list,不能修改list
        for (T t : list) {
            System.out.println(t);
        }

        // list.add(new Object()); // 编译器报错
    }

    public static void main(String[] args) {
        GInterfaceImpl gIterfaceImpl = new GInterfaceImpl();
        ArrayList<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("8");
        gIterfaceImpl.foo(list);
    }
}

 

"You're weak, bad guys most gentle of this world, and you come from the powerful."

Guess you like

Origin www.cnblogs.com/yanggb/p/10961968.html