有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

通过objecs字符串参数使用对象值对java哈希表进行排序

我有一个包含字符串键和类对象值的哈希表:

Hashtable<String,myclass>m_class_table = new Hashtable<String,myclass>();

在“myclass”中,我有一个字符串字段值

我需要根据这个字符串值对哈希表进行排序

我不能仅仅按照哈希表的值对它进行排序,因为它是一个对象

如何做到这一点

谢谢,这是事先准备好的


共 (2) 个答案

  1. # 1 楼答案

    aioobe的答案有一点不同:我会创建一个地图条目列表,并对该列表进行排序。这样,您仍然可以访问完整的地图条目

    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());
        }
    });
    
  2. # 2 楼答案

    I need to sort my hashtable according to this string value.

    哈希表不是排序数据结构

    您可以使用一些^{},例如^{},但这些数据结构会对键进行排序,因此,只有当键等于指向的对象的字符串字段时,这才有效

    I can't just sort it by the hashtable values beacuse it is an object..

    您需要提供一个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列表。(aList中的元素是有序的。)