Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

java - 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?

question from:https://stackoverflow.com/questions/65640964/classcastexception-when-using-treemap

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...