2009-11-15 54 views
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類。任何想法如何解決這個問題?

+0

你的意思是你不明白TreeMap的作用是什麼? – 2009-11-15 17:22:14

回答

3

TreeMap按其鍵值排序。您的地圖的鍵是字符串。你實際解決什麼問題?

0

該地圖是基於按鍵的排序(不是值),所以這就解釋了爲什麼你有一個字符串而不是動物。

0

您是幾乎那裏,如果你使用TreeSet中,而不是一個TreeMap,你可以用你的比較對畜禽類的領域之一。

順便說一下,如果Animal基類包含.getId()方法,那麼您正在使用反射到達Id字段,因此您可以投射和調用沒有反射的方法。

0

如果要排序Map的價值,而目前String關鍵實際上是Animal的屬性,那麼最好的辦法可能是基於一個SortedSet<Animal>或許這是使用Collections#sort()排序的List<Animal>創建LinkedHashMap

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

唯一的缺陷是,如果當你想要一個新的Animal添加到地圖中,你必須重新排序。