Karthik Dasari
Karthik Dasari

Reputation: 1

java.lang.ClassCastException: java.lang.Short cannot be cast to java.lang.Integer when sorting

How to sort hashmap by value if the values are Short type HashMap<Long, Short>()?

when I use generic sorting like

public static <K extends Comparable<K>, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
    Comparator<K> valueComparator =  new Comparator<K>() {
        public int compare(K k1, K k2) {
            int compare = map.get(k1).compareTo(map.get(k2));
            return compare != 0 ? compare : k1.compareTo(k2);
        }
    };
    Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
    sortedByValues.putAll(map);
    return sortedByValues;
}

I get this error:

java.lang.ClassCastException: java.lang.Short cannot be cast to java.lang.Integer

Upvotes: 0

Views: 1586

Answers (1)

Stephen C
Stephen C

Reputation: 719199

There are no explicit typecasts anywhere in this code.

Therefore, I conclude that the ClassCastException is caused by the implicit typecasts that the compiler inserts when you assign a value returned by some generic method to a variable with a specific type.

Furthermore, since the implicit typecasts only fail in circumstances where you have / someone has choosen to ignore or suppress Java compiler warnings about unsafe conversions, etcetera, I conclude that

  • this must have happened, and
  • it is the cause of your problem.

In short, the cause of problem is not in the code you have included in the question. It is somewhere else ...


In future, be sure to include:

  • Sufficient context to allow people to see how your code is being used. Ideally an MCVE.
  • The complete stacktrace for the exceptions.

Upvotes: 1

Related Questions