正如我们所知,SortedMap维护按键排序的条目。我在这个论坛上阅读了很多主题,并看到很多通过值来排序SortedMap的例子。然而,正如你所知道的,当我把一个项目放到默认的SortedMap中时,它不会再把这个新的条目放在它应该是的地方。按值维护SortedMap
例如,
SortedMap<String,Person> sortedMap = new TreeMap();
Person p1 = new Person("John",38);
sortedMap.put(p1.getName(), p1);
Person p2 = new Person("Tom",34);
sortedMap.put(p2.getName(), p2); // does not sort, maintains sorted set by comparing the other values
Person p3 = new Person("Susan",21);
sortedMap.put(p3.getName(), p3); // does not sort, maintains sorted set by comparing the other values
在这个论坛很多线程,我看到了很多很多的代码,通过调用一种方法一样排序由值的SortedMap:
sortedMap.sort(sortedMap.entries());
这或别的东西,方法被调用来获取排序的值。
但是,我需要一个Map实现,它使值保持排序而不需要调用排序方法,正如我在上面解释的。例如,在上面的代码中,我可以调用firstKey()方法;但是我需要调用firstValue()方法。
Person minimumAgePerson = sortedMap.firstValue().
System.out.println(minimumAgePerson.getName()); // it should print "Susan"
的SortedSet是不适合我的requiremenets,因为我可以把一些新的对象(人),其键值已经在地图上,这些刚刚添加的条目应覆盖现有的对象(所以我需要一个地图):
Person p4 = new Person("Susan",39);
sortedMap.put(p4.getName(),p4);
Person newMinimumAgePerson = sortedMap.firstValue();
System.out.println(newMinimumAgePerson.getName()); // it should print "Tom"
有没有实现这个taks或我需要实现SortedSet自己?
你为什么需要这样的事情?我相信你已经为你的任务选择了错误的数据结构,因为我可以想象,实际上没有应用按值排序的Map,其中某些其他结构无法使用(例如排序列表或其他)。 – bezmax 2013-05-14 14:38:45