ig = Graphs.synchronizedDirectedGraph( new DirectedSpa...">

Strange "template" syntax (generics?)

In the next line

Graph<Number,Number> ig = Graphs.<Number,Number>synchronizedDirectedGraph( new DirectedSparseMultigraph<Number,Number>()); 

Could you please explain what Graphs.<Number,Number>synchronizedDirectedGraph means? This is similar to calling the Graphs.synchronizedDirectedGraph method, but the boilerplate thing after the dot puzzles me (at least because of my C ++ background).

+4
source share
2 answers

The problem is that Java is not very smart where it supports type inference.

For the method:

 class A{} class B extends A{} class Y{ static <T> List<T> x(T t) } 

It displays the type List<B> from the parameter type B

 List<B> bs = Yx(new B()); 

But if you need List<A> , you need to drop B or add compiler hint:

 List<A> as1 = Y.<A> x(new B()); List<A> as2 = Yx((A) new B()); 

Part of the problem is that java generics are invariant, so List<B> not a subtype of List<A> .

+5
source

Specifies types for a static method. For more information, see General Types, Part 2 (in particular, the section "General Mesodes").

+6
source

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


All Articles