Java通过objecs字符串参数排序带有对象值的哈希表

| 我有一个包含字符串key和一个类对象值的hashable:
Hashtable<String,myclass>m_class_table = new Hashtable<String,myclass>();
在\'myclass \'里面,我有一个String字段值, 我需要根据此字符串值对哈希表进行排序。 我不能仅按哈希表值对其进行排序,因为它是一个对象。 如何才能做到这一点? 提前致谢。     
已邀请:
aioobe的答案略有不同:我会创建一个Map条目的列表并对该列表进行排序。这样,您仍然可以访问完整的地图条目。
Map<String, MyClass> map = new HashMap<String, MyClass>();
// add some entries

List<Entry<String,MyClass>> entryList = 
     new ArrayList<Entry<String,MyClass>>(map.entrySet());
Collections.sort(entryList, new Comparator<Entry<String,MyClass>>() {
    public int compare(
        Entry<String, MyClass> first, Entry<String, MyClass> second) {
            return first.getValue().getFoo()
                        .compareTo(second.getValue().getFoo());
    }
});
    
  我需要根据此字符串值对哈希表进行排序。 哈希表不是排序的数据结构。 您可以使用某些
SortedMap
,例如
TreeMap
,但是那些数据结构将按键排序,因此只有当键等于所指向对象的字符串字段时,该数据结构才起作用。   我不能仅按哈希表值对其进行排序,因为它是一个对象。 您需要提供
Comparator<myclass>
,或者让
myclass
实现
Comparable
接口。 根据您对哈希表的迭代方式,您可能会这样做:
List<myclass> myObjects = new ArrayList<myclass>(m_class_table.values());
Collections.sort(myObjects, new Comparator<myclass>() {
    @Override
    public int compare(myclass o1, myclass o2) {
        o1.stringField.compareTo(o2.stringField);
    }
});
然后遍历
myObjects
列表。 (订购了“ 9”中的元素。)     

要回复问题请先登录注册