1

这就是我所在的位置:

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上课。关于如何解决这个问题的任何想法?

4

4 回答 4

3

TreeMap 是根据它的键排序的。地图的键是字符串。你实际上在解决什么问题?

于 2009-11-15T17:20:11.637 回答
0

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

于 2009-11-15T17:20:58.217 回答
0

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

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

于 2009-11-15T17:44:46.787 回答
0

如果您想Map按值对 a 进行排序,并且当前String键实际上是 的属性Animal,那么最好的方法可能是LinkedHashMap基于 a创建 aSortedSet<Animal>或者List<Animal>使用排序的 a Collections#sort()

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

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

于 2009-11-15T18:14:46.663 回答