Search code examples
javatreemap

ClassCastException when using TreeMap


I have a TreeMap<Integer, TreeMap<int[][], Integer>> jungle. When I try to execute the statements

TreeMap<int[][], Integer> tempMap = new TreeMap();
int[][] matrix = {{1}};
tempMap.put(matrix, 4);

this last line gives me the

java.lang.ClassCastException: [[I cannot be cast to java.base/java.lang.Comparable at java.base/java.util.TreeMap.compare

exception. Am I not allowed to use an int[][] as a key in a treeMap?


Solution

  • The purpose of a TreeMap is to have an ordered collection

    A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

    You must pass a Comparator that deals with int[][]; here an example with one that sorted based on the full sum of the array

    class Custom2DArrayComparator implements Comparator<int[][]> {
    
        private static int sum(int[][] v) {
            return Arrays.stream(v).map(arr -> Arrays.stream(arr).sum())
                                   .mapToInt(Integer::intValue).sum();
        }
    
        @Override
        public int compare(int[][] o1, int[][] o2) {
            return Integer.compare(sum(o1), sum(o2));
        }
    }
    

    Use

    public static void main(String[] args) {
        TreeMap<int[][], Integer> tempMap = new TreeMap<>(new Custom2DArrayComparator());
        int[][] matrix = {{1}};
        tempMap.put(matrix, 4);
    }
    

    You can use the anonymous class to avoid creating a one outside

    public static void main(String[] args) {
        TreeMap<int[][], Integer> tempMap = new TreeMap<>(new Comparator<>() {
            @Override
            public int compare(int[][] o1, int[][] o2) {
                return Integer.compare(sum(o1), sum(o2));
            }
    
            int sum(int[][] v) {
                return Arrays.stream(v).map(arr -> Arrays.stream(arr).sum())
                    .mapToInt(Integer::intValue).sum();
            }
        });
        int[][] matrix = {{1}};
        tempMap.put(matrix, 4);
    }