新人求助,关于treemap 自定义 comparator
本菜鸟想自定义一个comparator 让treemap 的 key 倒序排列
public class Treesrt_sort2
{
public static void main(String[] args) {
//不指定排序器
TreeMap<String, String> treeMap1 = new TreeMap<String, String>();
treeMap1.put("2", "1");
treeMap1.put("b", "1");
treeMap1.put("1", "1");
treeMap1.put("a", "1");
System.out.println("treeMap1="+treeMap1);
//指定排序器
TreeMap<String, String> treeMap2 = new TreeMap<String, String>(new myComparator2());
treeMap2.put("2", "1");
treeMap2.put("b", "1");
treeMap2.put("1", "1");
treeMap2.put("a", "1");
System.out.println("treeMap2="+treeMap2);
}
}
class myComparator2 implements Comparator
{
@Override
public int compare(Object o1, Object o2)
{
String n1 = (String)o1;
String n2 = (String)o1;
// TODO Auto-generated method stub
return n2.compareTo(n1);
}
}
结果:第二个自定义的treepmap 有些元素消失了。
treeMap1={1=1, 2=1, a=1, b=1}
treeMap2={2=1}
我上网找了一些资料
当我把自定义comparator的定义在初始化treemap里面结果就变正常了
TreeMap<String, String> treeMap2 = new TreeMap<String, String>(new Comparator<String>(){
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
treeMap2.put("2", "1");
treeMap2.put("b", "1");
treeMap2.put("1", "1");
treeMap2.put("a", "1");
System.out.println("treeMap2="+treeMap2);
}
}
treeMap1={1=1, 2=1, a=1, b=1}
treeMap2={b=1, a=1, 2=1, 1=1}
请问各位大神,这是什么原因导致的?
------解决方案--------------------@Override
public int compare(Object o1, Object o2)
{
String n1 = (String)
o1;
String n2 = (String)
o1;