UPDATE: As Thomas mentioned, you can pass a custom Comparator to a TreeMap. So your original code can be work with a little modification:
Map<Integer[], Integer> map = new TreeMap<Integer[], Integer>(new IntegerWordComparator());
In this case, IntegerWordComparator will be something similar to IntegerWord (see below), but as an implementation of the Comparator interface:
public class IntegerWordComparator implements Comparator<Integer[]> {
@Override
public int compare(Integer[] iw1, Integer[] iw2) {
int commonLength = Math.min(iw1.length, iw2.length);
for (int i = 0; i < commonLength; i++) {
if (iw1[i] > iw2[i]) {
return 1;
} else if (iw1[i] < iw2[i]) {
return -1;
}
}
if (iw1.length > iw2.length) {
return 1;
} else if (iw1.length < iw2.length) {
return -1;
} else {
return 0;
}
}
}
Original answer
Use List instead of array, and HashMap instead of TreeMap:
Map<List<Integer>, Integer> map = new HashMap<List<Integer>, Integer>();
// add three items two of which are the same
map.put(Arrays.asList(new Integer[]{1, 2, 3}), 1);
map.put(Arrays.asList(new Integer[]{3, 4, 7}), 2);
map.put(Arrays.asList(new Integer[]{1, 2, 3}), 4);
// print the size
System.out.println(map.size()); // 2
If you want to ignore the order, then use Set as key.
If you really want to use TreeMap and you want to compare your arrays lexicographically, then you can write your own class and use it as a key. Here is an example:
public class IntegerWord implements Comparable<IntegerWord> {
protected final Integer[] integers;
public IntegerWord(Integer... integers) {
this.integers = integers;
}
@Override
public int compareTo(IntegerWord other) {
int commonLength = Math.min(integers.length, other.integers.length);
for (int i = 0; i < commonLength; i++) {
if (integers[i] > other.integers[i]) {
return 1;
} else if (integers[i] < other.integers[i]) {
return -1;
}
}
if (integers.length > other.integers.length) {
return 1;
} else if (integers.length < other.integers.length) {
return -1;
} else {
return 0;
}
}
@Override
public boolean equals(Object other) {
if (other instanceof IntegerWord) {
return (compareTo((IntegerWord)other) == 0);
} else {
return false;
}
}
@Override
public String toString() {
return Arrays.asList(integers).toString();
}
}
Usage:
Map<IntegerWord, Integer> map = new TreeMap<IntegerWord, Integer>();
map.put(new IntegerWord(2, 5), 11);
map.put(new IntegerWord(1, 2, 3), 22);
map.put(new IntegerWord(1, 2, 3, 4), 33);
map.put(new IntegerWord(1, 2, 3), 44); // 1, 2, 3 again!
map.put(new IntegerWord(3, 9, 3, 4), 55);
map.put(new IntegerWord(0, 1), 66);
map.put(new IntegerWord(), 77); // will be the first!
System.out.println(map);