I have a HashMap<Float[], Integer> and I'll probably need to convert it to TreeMap. How will keys (i.e. arrays) of TreeMap be sorted? By their first elements?
I was going to run a simple test but it resulted in error somehow:
public class treeMapTest {
public static void main(String[] args) {
Integer arr1[] = {9, 0, 3};
Integer arr2[] = {2, 2, 2};
Integer arr3[] = {4, 2, 1};
TreeMap<Integer[], Integer> tm = new TreeMap<Integer[], Integer>();
tm.put(arr1, 7);
tm.put(arr2, 7);
tm.put(arr3, 7);
System.out.println(tm);
}
}
Thank you.
Arrays don't have natural ordering (i.e. they don't implement the Comparable interface), which is why your code throws an exception when you instantiate the TreeMap using the parameterless constructor.
You must supply a Comparator<Integer[]> to the TreeMap constructor in order to define the ordering yourself.
BTW, using arrays as keys in a HashMap is a bad idea (since arrays don't override the default implementation of equals() and hashCode()), so it's a good thing you are switching to a TreeMap.
This might be syntactically correct but it's not practically useful.
The map uses equals() method to determine whether 2 keys are equal.
Arrays inherit equals() and hashcode() methods from Object class. Therefore when you want to search for a particular key(array object), you won't find it unless reference of the initial array object is passed.
For e.g.
Integer arr1[] = {9, 0, 3};
and
Integer arr1_copy[] = {9, 0, 3};
are 2 different objects and default equals() will fail.
If however, you need to use arrays as key, what you can do instead is create a class with an array as it's member and override hashcode() and equals() methods for this class and use this class as key.
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