[英]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>()
? 如果值是
Short
类型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
java.lang.ClassCastException:无法将java.lang.Short强制转换为java.lang.Integer
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. 因此,我得出的结论是,
ClassCastException
是由将某些通用方法返回的值分配给具有特定类型的变量时编译器插入的隐式类型转换引起的。
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 此外,由于隐式类型转换仅在您/某人选择忽略或禁止有关不安全转换等的Java编译器警告的情况下失败,因此我得出结论:
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: 将来,请确保包括:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.