I want to have some pairs of int in a TreeSet, and sort them by the first number.
Code test here:
public static void main (String[] args) throws java.lang.Exception
{
SortedSet<int[]> s = new TreeSet<int[]>(new Comparator<int[]>(){
public int compare(int[] a, int[] b) {
return b[0] - a[0];
}
});
int[] a = new int[]{1, 2};
int[] b = new int[]{1, 3};
s.add(a);
s.add(b);
System.out.println(s.size());
}
I don't know why the size of TreeSet turns out to be 1. Seems like the hashCode of a and b are same, but why?
Thanks for any help.
BTW: in fact, I was trying to put duplicate numbers in a set, which is not possible. Then I tried to have int pairs in a set. The first number is the actual number I want, the second number was there to prevent duplication. But I run into this problem.
It turns out to be 1 because your compare method only uses the first number in the array, and the two arrays you have both begin with 1. Therefore, from the point of view of the TreeSet, the two arrays are the same.
TreeSet.add returns
true if this set did not already contain the specified element
, and since the two values are considered equal (compare returns 0), the second value is not added and add() returns false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With