如何在Java中使用SortedMap接口? [英] How to use SortedMap interface in Java?
本文介绍了如何在Java中使用SortedMap接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个
Map<Float, MyObject>
使地图根据浮点数排序的最佳方法是什么?
What is the best way to keep the map sorted according to the float?
SortedMap
是最好的答案吗? TreeMap
?我该怎么用?
Is SortedMap
the best answer? TreeMap
? How do I use it?
我只创建一次地图,并经常使用myMap.put()
和myMap.get()
替换MyObject
.
I only create the map once and replace the MyObject
frequently using myMap.put()
and myMap.get()
.
推荐答案
我将使用实现SortedMap
的TreeMap
.正是为此目的而设计的.
I would use TreeMap
, which implements SortedMap
. It is designed exactly for that.
示例:
Map<Integer, String> map = new TreeMap<Integer, String>();
// Add Items to the TreeMap
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
// Iterate over them
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
请参见 SortedMap的Java教程页面.
并且此处是与TreeMap相关的教程列表.
See the Java tutorial page for SortedMap.
And here a list of tutorials related to TreeMap.
这篇关于如何在Java中使用SortedMap接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文