开发者

strange "template-like" syntax (generics?)

开发者 https://www.devze.com 2022-12-21 07:20 出处:网络
In the follow开发者_如何学编程ing line Graph<Number,Number> ig = Graphs.<Number,Number>synchronizedDirectedGraph(

In the follow开发者_如何学编程ing 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).


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


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>.

0

精彩评论

暂无评论...
验证码 换一张
取 消