2018年8月2日木曜日

What is Java’s wildcard type (with lower bounded or upper bounded)

Type parameters are used for Java collection classes and so on. Some of them have wild cards. The symbol "?" refers to it. It is explained that it points to "all types", but it is not very clear. In addition, there are upper bound type <? extends type> and lower bound type <? super type> that restrict the range of that type. I do not understand more and more? For example, the API specification of a method called merge in Java 's ConcurrentHashMap class is as follows:

  V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remap)

Oh no, it feels like. But first of all, let's examine what these types mean specifically. There was a good commentary on the following URL:

     https://www.thekingsmuseum.info/entry/2016/04/02/155821
     https://www.thekingsmuseum.info/entry/2016/04/19/232836

Based on that, I drew some figures. Will not it be quite clear this way? The first figure is a comparison between the Class type and the Generic type. The latter takes type parameters as arguments. For example, ArrayList <Double> means an ArrayList type with Double type objects as elements. Here, there is something to notice. The Class type on the left has super - sub inheritance relationship, but the right-hand side Generic type does not have it. That is, the inheritance relationship of the type parameter has no relation with Generic type.


Let's take a look at the following figure using a wild card "?" for the type parameter. For example, ArrayList <?> Is the supertype of all ArrayList <E> types.




Next is upper bounded wild card. For example, ArrayList <? extends Number> is a supertype of ArrayList whose type parameter is the Number class or its subclasses. It has no inheritance relation with other ArrayList types.


In addition, there is a lower bunded wild card. For example, ArrayList <? super Number> is a supertype of ArrayList whose type parameter is the Number class or its superclass. It has no inheritance relation with other ArrayList types


We will examine how these wildcards are effectively used in a separate document. Here I showed only the inheritance relationship of types, but with this alone, understanding of one step will advance.

0 件のコメント:

コメントを投稿