起初我写:private ArrayList<Integer> getDataList() { ArrayList<Integer> dataList = new ArrayList<>(LEN); for (int i = 0; i < LEN; i++) dataList.add(i); Collections.shuffle(dataList); return dataList;}后来我决定使用泛型:private <E> ArrayList<E> getDataList() { ArrayList<E> dataList = new ArrayList<>(LEN); for (int i = 0; i < LEN; i++) dataList.add(/* a procedure that generates E instance from index i*/); Collections.shuffle(dataList); return dataList;}接口中的静态方法不可覆盖,因此不能调用 E 上的静态方法来生成实例。如何重构它以使用泛型?谢谢。
1 回答
千万里不及你
TA贡献1784条经验 获得超9个赞
您需要提供一些作为方法参数进行创建的东西:
private <E> ArrayList<E> getDataList(IntFunction<? extends E> fn) {
然后:
dataList.add(fn.apply(i));
并像这样调用:
List<Integer> integerList = getDataList(Integer::valueOf); // Same output as non-generic code.
List<String> stringList = getDataList(i -> "Item " + i);
添加回答
举报
0/150
提交
取消