1

When I am passing an ArrayList to TreeSet constructor, I am getting the following error:

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)

I am getting the above error at this line :

TreeSet<Integer> set = new TreeSet(Arrays.asList(numbers));

This is the full program:

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));
}

}

What is it that I am doing wrong?

jay
  • 41
  • 4

2 Answers2

2

What Arrays.asList() actually returning is list of int array.

List<int[]> list = Arrays.asList(numbers);

You need to do the following.

TreeSet<Integer> set = Arrays.stream(number).boxed()
.collect(Collectors.toCollection(TreeSet::new));
Sherif Hamdy
  • 105
  • 1
  • 10
1

It is failing to do that because you can't have a TreeSet<int>, only a TreeSet<Integer>.

Because you did not specify a generic type for TreeSet, Arrays.asList tries to create a List<int[]>, which it succeeds. Why a int[]? You might ask. This is because int cannot be a generic type, so the generic parameter of asList is inferred to be int[], which can be a generic type. But then this list goes into TreeSet's constructor and TreeSet discovers that this is not a list of Integers, throwing an exception.

To fix this, you either change the parameter type from int[] to Integer[], or convert the int[] to a Integer[] before passing it into Arrays.asList.

TreeSet<Integer> set = new TreeSet<>(Arrays.stream(numbers).boxed().collect(Collectors.toList()));
Sweeper
  • 213,210
  • 22
  • 193
  • 313