Generics in java

An important goal of object-oriented is to reuse code, and an important mechanism to support this goal is generics;

1: Use interface types to represent generics

  For example, consider the problem of finding the largest item in an array of items. The basic code is type-independent, but it must have the ability to compare the size of any two objects and determine which one is larger and which one is larger. is small, so we can't directly find the largest element in the Object array, we need more information, the easiest is to compare the largest element in the array of Comparable, we can use CompareTo to determine the order, it is for all implementations Comparable The classes of the interface are all available, but this is not always feasible, because it is impossible for some classes in the class library to implement the interface. For example, a class may be a class in the library, but the interface is the user's own. Defined interface, and if a class is a final class, then it is impossible for us to extend it to create a new class, so this method is too limited,

2: Compatibility of array types

   One of the difficulties in language design is how to deal with the inheritance relationship of collection types. Suppose Employee iS-A Person, so does this also mean Employee[] IS-A Person[]? In other words, if a routine can allow Person[] to be passed as a parameter, can Employee[] be passed as a parameter to the routine?

  At first glance, this should not be a problem, it seems that Employee[] and Person[] should be compatible, but this problem is more complicated than we think, assuming that in addition to Employee, we have Student IS-A Person, this Consider the following two statements

//Test the covariance of the array
    /**
     * When declaring an array's type as a superclass it can apply any type of its subclasses
     * When compiling, Employee is a Person class that is compiled by
     * but throws a runtime exception error when running
     * java.lang.ArrayStorexception
     * The covariance of the array causes the compilation to pass but causes the following runtime exception error
     * The whole point of using generics is to generate compile errors rather than runtime exceptions
     * , so generic collections are not covariant
     */
    public void test(){
        Person [] p = new Employee[5];
        p[0] = new Student("Student");
        p[1] = new Employee("Employee");
        System.out.println(p[0].toString());
        System.out.println(p[1].toString());

    }

 Covariant:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325022042&siteId=291194637