【发布时间】:2016-02-10 05:50:18
【问题描述】:
我有一个方法,它接收一个 T 类型的集合作为参数,并返回一个整数类型的集合。在这个特定的例子中,我试图返回一个 ArrayList(我这样做错了吗?我想既然 ArrayList 继承自 Collection,那应该没问题)。
@Test public void test() {
Collection<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(8);
list.add(7);
list.add(3);
list.add(4);
Comparison comp = new Comparison();
int low = 1;
int high = 5;
ArrayList<Integer> actual = SampleClass.<Integer>range(list, low, high, comp);
ArrayList<Integer> expected = new ArrayList<Integer>();
expected.add(2);
expected.add(3);
expected.add(4);
Assert.assertEquals(expected, actual);
}
我在这里做错了什么?
编辑:
根据要求,这里是讨论的方法:
public static <T> Collection<T> range(Collection<T> coll, T low, T high,
Comparator<T> comp) {
if (coll == null || comp == null) {
throw new IllegalArgumentException("No Collection or Comparator.");
}
if (coll.size() == 0) {
throw new NoSuchElementException("Collection is empty.");
}
ArrayList<T> al = new ArrayList<T>();
for (T t : coll) {
if (comp.compare(t, low) >= 0 && comp.compare(t, high) <= 0) {
al.add(t);
}
}
return al;
}
【问题讨论】:
-
错误是什么?您能否粘贴 SampleClass.range 的代码。
-
它给了我一个不兼容的类型错误:不兼容的类型:Collection
无法转换为 ArrayList -
ArrayList<Integer> actual = new ArrayList<>(SampleClass.<Integer>range(list, low, high, comp));? -
这似乎奏效了。谢谢!你能解释一下这背后的语法吗?
-
@Alvarno Collection
不能分配给 ArrayList 。您需要添加演员表或按照安迪的建议进行操作。也就是说,您能否展示采用 Collection 并返回 Collection 的方法?
标签: java unit-testing generics arraylist collections