Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange "template-like" syntax (generics?)

Tags:

java

generics

In the following line

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

could you please explain what Graphs.<Number,Number>synchronizedDirectedGraph means ? It looks like a call to a method Graphs.synchronizedDirectedGraph, but the template-like thingie after the dot puzzles me (at least due to my C++ background).

like image 275
Stefano Borini Avatar asked Dec 22 '22 05:12

Stefano Borini


2 Answers

It is specifying the types for the static method. See Generic Types, Part 2 (particularly the "Generic mehods" section) for more information.

like image 115
Matthew Flaschen Avatar answered Jan 08 '23 19:01

Matthew Flaschen


The problem is that Java is not very intelligent in the places it supports type inference.

For a method:

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

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

List<B> bs = Y.x(new B());

But if you need List<A> you have to cast B or add the compiler hint:

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

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

like image 26
Thomas Jung Avatar answered Jan 08 '23 20:01

Thomas Jung