How does JDK 8 type output work with generic?

I have code that could not be compiled using JDK 7, but it can be compiled using JDK 8.

For abstract actual code:

interface A {
...
}

class B implements A {
...
}

public void AAA(List<A> list) {...}

AAA(Collections.singletonList(new B()));

Collections.singletonList is defined as

public static <T> List<T> singletonList(T o) {
    return new SingletonList<>(o);
}

So, as far as I know, based on generic, T will be inferred to B, so Collections.singletonList (new B ()) will be a List, which cannot be assigned to a List, since Java generic is invariant.

But with JDK 8 T is output to A and compilation succeeds.

I would like to know how T is displayed on A, since there are two variables for type T: A and B.

Is there a priority order? Or does the compiler find a common class of ancestors?

Attaching an official document is much appreciated!

Thanks in advance!

ps1. JDK version 7 is Oracle 1.7.0_79, and JDK version 8 is Oracle 1.8.0_66.

ps2. :

https://github.com/apache/storm/blob/85a31e2fdec1ffef83e1ff438cd765a821fb06e4/examples/storm-opentsdb-examples/src/main/java/org/apache/storm/opentsdb/SampleOpenTsdbBoltTopology.java#L48

https://github.com/apache/storm/blob/85a31e2fdec1ffef83e1ff438cd765a821fb06e4/external/storm-opentsdb/src/main/java/org/apache/storm/opentsdb/bolt/OpenTsdbBolt.java#L77

https://github.com/apache/storm/blob/85a31e2fdec1ffef83e1ff438cd765a821fb06e4/external/storm-opentsdb/src/main/java/org/apache/storm/opentsdb/bolt/TupleOpenTsdbDatapointMapper.java#L37

+6
3

, , §18. Type Inference, , . , , :

Java SE 7 Edition Java® :

  • - .
  • , . .
  • , .
  • ( ) ( ).
  • , , , , .
  • ( ) .
  • . . , , .
  • : .

. , , , AAA .

, , AAA . List<A>. " ", , , (B) (A).

+5

.

, ...

,

 AAA(Collections.singletonList(new B())); // returns List<A> NOT List<B>

jdk-7 , T B, .

+4

" " http://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html

Java SE 8. , , , , processStringList.

AAA A, , , AAA(), A, Java8 A over B ?

0

Source: https://habr.com/ru/post/1014226/


All Articles