【问题标题】:Creating an universal comparator to sort a tree map problem创建一个通用比较器来对树形图问题进行排序
【发布时间】:2009-11-15 17:18:09
【问题描述】:

这就是我所在的地方:

public final Comparator<Object> ID_IGN_CASE_COMP = new Comparator<Object>() {

    public int compare(Object o1, Object o2) {
        String s1 = null;
        String s2 = null;
        try {
            Class c = o1.getClass();
            IO.println(c.getName()); //java.lang.string instead of Animal
            Method method = c.getMethod("getId");
            s1 = (String)method.invoke(o1);
            s2 = (String)method.invoke(o2);
        } catch (NoSuchMethodException e) {
        } catch (IllegalAccessException e) {
        } catch (InvocationTargetException e) {}
        return s1.compareToIgnoreCase(s2);
    }
};

private Map< String, Animal> _animals = new TreeMap< String, Animal>(ID_IGN_CASE_COMP);

我得到的是 java.lang.string 而不是 Animal 类。关于如何解决此问题的任何想法?

【问题讨论】:

  • 您的意思是您不了解 TreeMap 的用途是什么?

标签: java comparator treemap


【解决方案1】:

TreeMap 是根据它的键来排序的。地图的键是字符串。你真正解决了什么问题?

【讨论】:

    【解决方案2】:

    地图基于键(而不是值)的顺序,所以这就解释了为什么你有一个字符串而不是一个动物。

    【讨论】:

      【解决方案3】:

      几乎在那里,如果您使用 TreeSet 而不是 TreeMap,则可以在 Animal 类的某个字段上使用比较器。

      顺便说一句,您正在使用反射来获取 Id 字段,如果 Animal 基类包含 .getId() 方法,您可以强制转换并调用该方法而无需反射。

      【讨论】:

        【解决方案4】:

        如果您想按值对Map 进行排序,并且当前的String 键实际上是Animal 的属性,那么最好的方法可能是基于SortedSet&lt;Animal&gt; 创建一个LinkedHashMap 或者也许使用Collections#sort() 排序的List&lt;Animal&gt;

        Set<Animal> animalSet = createAndSortItSomehow();
        Map<String, Animal> animalMap = new LinkedHashMap<String, Animal>();
        for (Animal animal : animalSet) {
            animalMap.put(animal.getSomeStringYouWantAsKey(), animal);
        }
        

        唯一的缺陷是,如果您想在地图中添加新的Animal,则必须重新排序。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-09-14
          • 1970-01-01
          • 2013-06-01
          • 1970-01-01
          • 2015-07-09
          • 1970-01-01
          • 2015-10-07
          相关资源
          最近更新 更多