欢迎光临! 所以,我目前正在研究Collection to array converter,但我遇到了问题。
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方法。
答案 0 :(得分:4)
如果您将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));
答案 1 :(得分:1)
Collection<Object>
不是Collection<Integer>
,并且不能转换为一个。但是,如果通过使元素类型通用来告诉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;
}