java TreeMap 中的key是怎么排序的呢? 如果说key是 Double 类型的,自动排序的结果是从小到大的么
用Double类型做key可以准确排序吗,会有误差吗。如果KEY1=0.1002KEY2=0.1102KEY3=0.1003,排完序的顺序是什么...
用Double 类型做key 可以准确排序吗,会有误差吗。
如果 KEY1 = 0.1002
KEY2 = 0.1102
KEY3 = 0.1003, 排完序的顺序是什么 展开
如果 KEY1 = 0.1002
KEY2 = 0.1102
KEY3 = 0.1003, 排完序的顺序是什么 展开
展开全部
可以的,你可以看下TreeMap API帮助文档的介绍
例子如下
@Test
public void test() {
TreeMap<Double,String> treeMap = new TreeMap();
treeMap.put(0.1003, "zhangsan");
treeMap.put(1.1, "lisi");
treeMap.put(1.00031, "wangwu");
treeMap.put(0.1102, "xiaohong");
Set<Entry<Double, String>> entry = treeMap.entrySet();
for(Iterator<Entry<Double,String>> it = entry.iterator();it.hasNext();) {
Entry<Double, String> entry2 = it.next();
System.err.println("KEY:"+entry2.getKey()+" "+"VALUE:"+entry2.getValue());
}
}
------------------------------------
运行结果:
KEY:0.1003 VALUE:zhangsan
KEY:0.1102 VALUE:xiaohong
KEY:1.00031 VALUE:wangwu
KEY:1.1 VALUE:lisi
按照大小排序了
例子如下
@Test
public void test() {
TreeMap<Double,String> treeMap = new TreeMap();
treeMap.put(0.1003, "zhangsan");
treeMap.put(1.1, "lisi");
treeMap.put(1.00031, "wangwu");
treeMap.put(0.1102, "xiaohong");
Set<Entry<Double, String>> entry = treeMap.entrySet();
for(Iterator<Entry<Double,String>> it = entry.iterator();it.hasNext();) {
Entry<Double, String> entry2 = it.next();
System.err.println("KEY:"+entry2.getKey()+" "+"VALUE:"+entry2.getValue());
}
}
------------------------------------
运行结果:
KEY:0.1003 VALUE:zhangsan
KEY:0.1102 VALUE:xiaohong
KEY:1.00031 VALUE:wangwu
KEY:1.1 VALUE:lisi
按照大小排序了
展开全部
import java.util.Comparator;
import java.util.TreeMap;
public class MapPaixu {
public static void main(String[] args) {
TreeMap<Double, Integer> map2 = new TreeMap<Double, Integer>(new Comparator<Double>() {
@Override
public int compare(Double o1, Double o2) {
return o2.compareTo(o1);
}
});
map2.put(1.3, 2);
map2.put(1.2, 4);
map2.put(-2.02133, 3);
map2.put(1.1, 1);
map2.put(1.8, 2);
map2.put(-1.01, 3);
System.out.println("逆序排列:"+map2);
}
}
运行结果:
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询