当我将ArrayList传递给TreeSet构造函数时,出现以下错误:
Exception in thread "main" java.lang.ClassCastException: [I cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1294)
at java.util.TreeMap.put(TreeMap.java:538)
at java.util.TreeSet.add(TreeSet.java:255)
at java.util.AbstractCollection.addAll(AbstractCollection.java:344)
at java.util.TreeSet.addAll(TreeSet.java:312)
at java.util.TreeSet.<init>(TreeSet.java:160)
at jay.week1.MaxPairwiseProduct.getMaxPairwiseProduct(MaxPairwiseProduct.java:8)
at jay.week1.MaxPairwiseProduct.main(MaxPairwiseProduct.java:17)
我在此行收到上述错误:
TreeSet<Integer> set = new TreeSet(Arrays.asList(numbers));
这是完整的程序:
import java.util.*;
public class MaxPairwiseProduct {
static int getMaxPairwiseProduct(int[] numbers) {
TreeSet<Integer> set = new TreeSet(Arrays.asList(numbers));
int max1 = set.pollLast();
int max2 = set.pollLast();
int result = max1 * max2;
return result;
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
System.out.println(getMaxPairwiseProduct(numbers));
}
}
我做错了什么事?
最佳答案
Arrays.asList()实际返回的是int数组的列表。
List<int[]> list = Arrays.asList(numbers);
您需要执行以下操作。
TreeSet<Integer> set = Arrays.stream(number).boxed()
.collect(Collectors.toCollection(TreeSet::new));