Jenis kebergantungan di Java, Bahagian 2

Memahami keserasian jenis adalah asas untuk menulis program Java yang baik, tetapi interaksi varians antara elemen bahasa Java dapat dilihat sangat akademik bagi yang belum tahu. Artikel dua bahagian ini adalah untuk pembangun perisian yang bersedia menangani cabaran! Bahagian 1 mengungkapkan hubungan kovarian dan kontroversi antara elemen yang lebih mudah seperti jenis larik dan jenis generik, serta elemen bahasa khas Java, wildcard. Bahagian 2 menerangkan jenis ketergantungan dalam Java Collections API, dalam generik, dan dalam ungkapan lambda.

Kami akan melompat masuk, jadi jika anda belum membaca Bahagian 1, saya cadangkan untuk memulakannya.

Contoh API untuk pelanggaran

Sebagai contoh pertama kami, pertimbangkan Comparatorversi java.util.Collections.sort()dari Java Collections API. Tandatangan kaedah ini adalah:

  void sort(List list, Comparator c) 

The sort()Cara menyusun apa-apa List. Biasanya lebih mudah menggunakan versi yang terlalu banyak, dengan tandatangan:

 sort(List
    
     ) 
    

Dalam kes ini, extends Comparablemenyatakan bahawa hal sort()itu dapat dipanggil hanya jika elemen membandingkan kaedah yang diperlukan (yaitu compareTo)telah ditentukan dalam jenis elemen (atau dalam jenis supertipe, berkat :? super T)

 sort(integerList); // Integer implements Comparable sort(customerList); // works only if Customer implements Comparable 

Menggunakan generik untuk perbandingan

Jelas sekali, senarai dapat disusun hanya jika elemennya dapat dibandingkan antara satu sama lain. Perbandingan dilakukan dengan kaedah tunggal compareTo, yang tergolong dalam antara muka Comparable. Anda mesti melaksanakan compareTodalam kelas elemen.

Jenis elemen ini boleh disusun hanya dengan satu cara. Sebagai contoh, anda boleh menyusun Customermengikut ID mereka, tetapi tidak mengikut tarikh lahir atau poskod. Menggunakan Comparatorversi sort()lebih fleksibel:

 publicstatic  void sort(List list, Comparator c) 

Sekarang kita membandingkan elemen bukan dalam kelas elemen, tetapi pada Comparatorobjek tambahan . Antara muka generik ini mempunyai satu kaedah kaedah:

 int compare(T o1, T o2); 

Parameter kontravarian

Membuat objek lebih dari sekali membolehkan anda menyusun objek menggunakan kriteria yang berbeza. Tetapi adakah kita benar-benar memerlukan Comparatorparameter jenis yang rumit ? Dalam kebanyakan kes, Comparatorsudah cukup. Kita dapat menggunakan compare()kaedahnya untuk membandingkan dua elemen dalam Listobjek, seperti berikut:

class DateComparator melaksanakan Comparator {public int membandingkan (Date d1, Date d2) {return ...} // membandingkan dua objek Date} List dateList = ...; // Senarai objek Tarikh semacam (DateList, DateComparator baru ()); // senarai tarikh

Collection.sort()Walau bagaimanapun, menggunakan kaedah yang lebih rumit menyediakan kami untuk kes penggunaan tambahan. Parameter jenis kontravarian Comparablememungkinkan untuk menyusun senarai jenis List, kerana java.util.Datemerupakan jenis supertype java.sql.Date:

 List sqlList = ... ; sort(sqlList, new DateComparator()); 

Sekiranya kita menghilangkan perbezaan dalam sort()tandatangan (hanya menggunakan atau yang tidak ditentukan, tidak selamat ), maka penyusun menolak baris terakhir sebagai kesalahan jenis.

Untuk memanggil

 sort(sqlList, new SqlDateComparator()); 

anda perlu menulis kelas tanpa ciri tambahan:

 class SqlDateComparator extends DateComparator {} 

Kaedah tambahan

Collections.sort()bukan satu-satunya kaedah Java Collections API yang dilengkapi dengan parameter kontravarian. Kaedah suka addAll(), binarySearch(), copy(), fill(), dan sebagainya, boleh digunakan dengan fleksibiliti yang sama.

Collectionskaedah seperti max()dan min()menawarkan jenis hasil yang berbeza:

 public static 
    
      T max( Collection collection) { ... } 
    

Seperti yang anda lihat di sini, parameter jenis dapat diminta untuk memenuhi lebih dari satu syarat, hanya dengan menggunakan &. Yang extends Objectmungkin muncul diperlukan, tetapi ia menetapkan bahawa max()pulangan hasil jenis Objectdan tidak baris Comparabledalam bytecode. (Tidak ada parameter jenis dalam kod bytec.)

Versi max()dengan Comparatoryang lebih muatan lebih lucu:

 public static  T max(Collection collection, Comparator comp) 

Ini max()mempunyai parameter jenis kontravarian dan kovarian. Walaupun unsur-unsur yang Collectionmesti ada (mungkin berbeza) subtipe dari jenis tertentu (tidak diberikan secara eksplisit), Comparatormesti dijadikan contoh untuk supertype dari jenis yang sama. Banyak yang diperlukan dari algoritma inferensi penyusun, untuk membezakan jenis antara antara panggilan seperti ini:

 Collection collection = ... ; Comparator comparator = ... ; max(collection, comparator); 

Mengikat parameter jenis kotak

Sebagai contoh terakhir dari ketergantungan jenis dan varians dalam Java Collections API, mari kita pertimbangkan semula tandatangan sort()dengan Comparable. Perhatikan bahawa ia menggunakan kedua extends- duanya dan super, yang dikotak:

 static 
    
      void sort(List list) { ... } 
    

In this case, we're not as interested in the compatibility of references as we are in binding the instantiation. This instance of the sort() method sorts a list object with elements of a class implementing Comparable. In most cases, sorting would work without in the method's signature:

 sort(dateList); // java.util.Date implements Comparable sort(sqlList); // java.sql.Date implements Comparable 

The lower bound of the type parameter allows additional flexibility, however. Comparable doesn't necessarily need to be implemented in the element class; it's enough to have implemented it in the superclass. For example:

 class SuperClass implements Comparable { public int compareTo(SuperClass s) { ... } } class SubClass extends SuperClass {} // without overloading of compareTo() List superList = ...; sort(superList); List subList = ...; sort(subList); 

The compiler accepts the last line with

 static 
    
      void sort(List list) { ... } 
    

and rejects it with

static 
    
      void sort(List list) { ... } 
    

The reason for this rejection is that the type SubClass (which the compiler would determine from the type List in the parameter subList) is not suitable as a type parameter for T extends Comparable. The type SubClass doesn't implement Comparable; it only implements Comparable. The two elements are not compatible due to the lack of implicit covariance, although SubClass is compatible to SuperClass.

On the other hand, if we use , the compiler doesn't expect SubClass to implement Comparable; it's enough if SuperClass does it. It's enough because the method compareTo() is inherited from SuperClass and can be called for SubClass objects: expresses this, effecting contravariance.

Contravariant accessing variables of a type parameter

The upper or the lower bound applies only to type parameter of instantiations referred by a covariant or contravariant reference. In the case of Generic covariantReference; and Generic contravariantReference;, we can create and refer objects of different Generic instantiations.

Different rules are valid for the parameter and result type of a method (such as for input and output parameter types of a generic type). An arbitrary object compatible to SubType can be passed as parameter of the method write(), as defined above.

 contravariantReference.write(new SubType()); // OK contravariantReference.write(new SubSubType()); // OK too contravariantReference.write(new SuperType()); // type error ((Generic)contravariantReference).write( new SuperType()); // OK 

Because of contravariance, it's possible to pass a parameter to write(). This is in contrast to the covariant (also unbounded) wildcard type.

The situation doesn't change for the result type by binding: read() still delivers a result of type ?, compatible only to Object:

 Object o = contravariantReference.read(); SubType st = contravariantReference.read(); // type error 

The last line produces an error, even though we've declared a contravariantReference of type Generic.

The result type is compatible to another type only after the reference type has been explicitly converted:

 SuperSuperType sst = ((Generic)contravariantReference).read(); sst = (SuperSuperType)contravariantReference.read(); // unsafer alternative 

Examples in the previous listings show that reading or writing access to a variable of type parameter behaves the same way, regardless of whether it happens over a method (read and write) or directly (data in the examples).

Reading and writing to variables of type parameter

Table 1 shows that reading into an Object variable is always possible, because every class and the wildcard are compatible to Object. Writing an Object is possible only over a contravariant reference after appropriate casting, because Object is not compatible to the wildcard. Reading without casting into an unfitting variable is possible with a covariant reference. Writing is possible with a contravariant reference.

Table 1. Reading and writing access to variables of type parameter

reading

(input)

read

Object

write

Object

read

supertype   

write

supertype   

read

subtype    

write

subtype    

Wildcard

?

 OK  Error  Cast  Cast  Cast  Cast

Covariant

?extends

 OK  Error  OK  Cast  Cast  Cast

Contravariant

?super

 OK  Cast  Cast  Cast  Cast  OK

The rows in Table 1 refer to the sort of reference, and the columns to the type of data to be accessed. The headings of "supertype" and "subtype" indicate the wildcard bounds. The entry "cast" means the reference must be casted. An instance of "OK" in the last four columns refers to the typical cases for covariance and contravariance.

See the end of this article for a systematic test program for the table, with detailed explanations.

Creating objects

On the one hand, you cannot create objects of the wildcard type, because they are abstract. On the other hand, you can create array objects only of an unbounded wildcard type. You cannot create objects of other generic instantiations, however.

 Generic[] genericArray = new Generic[20]; // type error Generic[] wildcardArray = new Generic[20]; // OK genericArray = (Generic[])wildcardArray; // unchecked conversion genericArray[0] = new Generic(); genericArray[0] = new Generic(); // type error wildcardArray[0] = new Generic(); // OK 

Because of the covariance of arrays, the wildcard array type Generic[] is the supertype of the array type of all instantiations; therefore the assignment in the last line of the above code is possible.

Within a generic class, we cannot create objects of the type parameter. For example, in the constructor of an ArrayList implementation, the array object must be of type Object[] upon creation. We can then convert it to the array type of the type parameter:

 class MyArrayList implements List { private final E[] content; MyArrayList(int size) { content = new E[size]; // type error content = (E[])new Object[size]; // workaround } ... } 

For a safer workaround, pass the Class value of the actual type parameter to the constructor:

 content = (E[])java.lang.reflect.Array.newInstance(myClass, size); 

Multiple type parameters

A generic type can have more than one type parameter. Type parameters don't change the behavior of covariance and contravariance, and multiple type parameters can occur together, as shown below:

 class G {} G reference; reference = new G(); // without variance reference = new G(); // with co- and contravariance 

The generic interface java.util.Map is frequently used as an example for multiple type parameters. The interface has two type parameters, one for key and one for value. It's useful to associate objects with keys, for example so that we can more easily find them. A telephone book is an example of a Map object using multiple type parameters: the subscriber's name is the key, the phone number is the value.

The interface's implementation java.util.HashMap has a constructor for converting an arbitrary Map object into an association table:

 public HashMap(Map m) ... 

Because of covariance, the type parameter of the parameter object in this case does not have to correspond with the exact type parameter classes K and V. Instead, it can be adapted through covariance:

 Map customers; ... contacts = new HashMap(customers); // covariant 

Di sini, Idadalah supertype CustomerNumber, dan Personsupertype dari Customer.

Varians kaedah

Kami telah membincangkan variasi jenis; sekarang mari kita beralih ke topik yang lebih mudah.