gpt4 book ai didi

java - 将泛型 Collection 转换为 Collection
转载 作者:行者123 更新时间:2023-11-30 06:03:14 26 4
gpt4 key购买 nike

欢迎!所以,我目前正在研究集合到数组转换器,但我遇到了问题。

    private static Collection<Object> resolveDesiredCollection(String desiredCollection){
if (desiredCollection == null || desiredCollection.equals("")){
desiredCollection = "al";
}
Collection<Object> collection;
switch (desiredCollection) {
case "al":
collection = new ArrayList<>();
break;
case "all":
collection = new LinkedList<>();
break;
case "hs":
collection = new HashSet<>();
break;
case "ts":
collection = new TreeSet<>();
break;
default:
collection = new ArrayList<>();
}
return collection;
}

public static Collection<Integer> intArrayToCollection(int [] array, String
desiredCollection){

Collection<Integer> collection = (Collection<Integer>)
(resolveDesiredCollection(desiredCollection));

Arrays.stream(array).forEach(i -> collection.add(new Integer(i)));

return collection;
}

我怎样才能转换它?显示的方式不起作用,因为编译器尖叫着“不可转换类型”,这甚至可能吗?我想避免代码重复,所以我不想为 Integer、Double、String 等创建resolveDesiredCollection 方法。

最佳答案

如果您创建 resolveDesiredCollection方法通用:

private static <T> Collection<T> resolveDesiredCollection(String desiredCollection)
{
if (desiredCollection == null || desiredCollection.equals("")) {
desiredCollection = "al";
}
Collection<T> collection;
switch (desiredCollection) {
case "al":
collection = new ArrayList<>();
break;
case "all":
collection = new LinkedList<>();
break;
case "hs":
collection = new HashSet<>();
break;
case "ts":
collection = new TreeSet<>();
break;
default:
collection = new ArrayList<>();
}
return collection;
}

您可以简单地调用它:

Collection<Integer> collection = resolveDesiredCollection(desiredCollection);

你的第二种方法也可以变得通用:

public static <T> Collection<T> ArrayToCollection(T[] array, String desiredCollection)
{
Collection<T> collection = resolveDesiredCollection(desiredCollection);

Arrays.stream(array).forEach(i -> collection.add(i));

return collection;
}

当然,您可以消除这些方法并使用现有的JDK方法来实现相同的功能。

例如,要转换 Integer[]ArrayList<Integer> :

ArrayList<Integer> list =
Arrays.stream(array).collect(Collectors.toCollection(ArrayList::new));

关于java - 将泛型 Collection<Object> 转换为 Collection<Integer>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52719234/

26 4 0