我们可以在Java泛型中创建一个Type类对象,如T t = new T();
这是我的代码,
public class Graph<T extends NeighbourInt<T>> {
Map<String, List<T>> adjecencyList;
public Graph() {
adjecencyList = new HashMap<>();
}
public void addEdge(String vertex1, String vertex2, int weight) {
if (adjecencyList.containsKey(vertex1)) {
List<T> neg = adjecencyList.get(vertex1);
neg.add(new T (vertex2, weight));
} else {
List<T> neg = new ArrayList<>();
neg.add(new T(vertex2, weight));
adjecencyList.put(vertex1, neg);
}
}
}
我的NeighbourInt界面
public interface NeighbourInt<T> extends Comparable<T> {
public String getVertex();
public void setVertex(String vertex);
public int getWeight();
public void setWeight(int weight);
}
是否有可能启动像新T()的对象;在Java Generics中?
答案 0 :(得分:3)
不,还没(因为擦除,再次)
但是,Graph
的构造函数可以接受一个从(String,int)创建T
的生成器;当您需要创建新的T
时,请调用此生成器。
在java 8中,你可以做到
public Graph( BiFunction<String,Integer,T> generator )
当您需要创建T
时,请执行generator.apply(string,integer)
假设你有一个NeighbourInt子类型的构造函数
public Foo(String, int)
你可以做到
new Graph<>( Foo::new )
答案 1 :(得分:2)
没有。实际上,T
是泛型类型的参数,而不是类。
例如:
public interface NeighbourInt extends Comparable<NeighbourInt> {
// ...
}
上面的代码将NeighbourInt
声明为Comparable
,参数为NeighbourInt
。
由于Comparable
接口定义为:
public interface Comparable<T> {
int compareTo(T o);
}
参数化Comparable<NeighbourInt>
将等同于具有以下方法的接口:
int compareTo(NeighbourInt o);
因此上面声明的NeighbourInt
继承了该方法。
编辑:将泛型类视为类&#34;类&#34;的工厂,作为制造其他类的类。因此,只有在需要制作许多&#34;制造的&#34;不同类型的类作为参数。
声明:
public class Graph<T extends NeighbourInt> {
// ...
}
只有在您拥有多种&#34;类型的图表时才有意义,例如:
Graph<Node> graph;
Graph<WeightedNode> weightedGraph;
// and so on...
如果您的图表只有NeighbourInt
s,那么您的第一个选择就是写:
public class Graph {
// this is where you set the generic parameter
Map<String, List<NeighbourInt>> adjecencyList;
// ...
}