Comparator for TreeMap<Integer[], Double>

Hi all,

I'm trying to write a compartor for a TreeMap<Integer[], Double>. The Integer[] has always two entries and [x,y] should be equal to [y,x].

This is my code:

TreeMap<Integer[], Double> t =new TreeMap<Integer[], Double>(new Comparator(){

publicint compare(Object o1, Object o2){

Integer[] i1 = (Integer[]) o1;

Integer[] i2 = (Integer[]) o2;

if (i1[0].equals(i2[0]) && i1[1].equals(i2[1]))

return 0;

if (!i1[0].equals(i2[0]))

return i1[0].compareTo(i2[0]);

return i1[1].compareTo(i2[1]);

}

});

However, after inserting two elements like

t.put(new Integer[]{1,2}, 0.1);

t.put(new Integer[]{2,1}, 0.2);

, the TreeMap contains these two elements instead of just one.

Is there an error in my Comparator?

Regards,

Andreas

[1448 byte] By [andreassa] at [2007-10-3 4:40:22]
# 1
the two elements are inside your map because their keys new Integer[]{1,2} and new Integer[]{2,1} are different, so they represent different values.To make this simpler, one possibility is to create a wrapper class for these two integers, and override equals()
lfschucka at 2007-7-14 22:44:20 > top of Java-index,Core,Core APIs...
# 2
But in the comparator, I compare the values of the two integers and return 0 if they are the same. Shouldn't therefore the two keys be the same?
schlandia at 2007-7-14 22:44:20 > top of Java-index,Core,Core APIs...
# 3
I found my error. I forgot to check whether i1[0] == i2[1] and i1[1] == i2[0].Thanks
schlandia at 2007-7-14 22:44:20 > top of Java-index,Core,Core APIs...
# 4
Btw., you should type your comparator (Comparator<Integer[]>), which saves you from casting and getting a compiler warning.
stefan.schulza at 2007-7-14 22:44:20 > top of Java-index,Core,Core APIs...