【发布时间】:2018-01-02 03:33:02
【问题描述】:
我有这两种逻辑相同但参数不同的方法。如何将它们变成一种通用方法?
boolean exists(int[][] roads, int[] road){
for(int[] r: roads){
// code
}
return false;
}
boolean exists(ArrayList<int[]> roads, int[] road){
for(int[] r: roads){
// code
}
return false;
}
我想做这样的事情
<T> boolean exists(Collection<T[]> roads, T[] road){
for(T[] r: roads){
if(r[0] == road[0])
return true;
}
return false;
}
我收到如下类型错误:
required: Collection<T[]>,T[]
found: int[][],int[]
reason: cannot infer type-variable(s) T
(argument mismatch; int[][] cannot be converted to Collection<T[]>)
where T is a type-variable:
T extends Object declared in method <T>exists(Collection<T[]>,T[])
我也尝试了其他一些签名,但它们也不起作用
<T,F> boolean exists(F<T[]> roads, T[] road)<T,F> boolean exists(F<? extends Object> roads, T[] road)
【问题讨论】:
-
FWIW:
X[]永远不是Collection<X>。 -
让一种方法调用另一种方法。这样你只需要维护一个实现,但外部代码仍然可以调用对它们更方便的任何方法。
标签: java arrays generics arraylist