views:

169

answers:

5

This is where I'm at:

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);

I'm getting java.lang.string instead of Animal class. Any idea on how can I solve this issue?

+2  A: 

The TreeMap is ordered in terms of its keys. The keys of your map are Strings. What problem are you actually solving?

Jonathan Feinberg
A: 

The Map is based on the ordering of the keys (not values), so that explains why you've got a String instead of an Animal.

Jeff Foster
A: 

Bah, that's the problem. I needed to sort by a field of a value. Guess i'll have to sort a collection then

d0pe
A: 

You are almost there, If you use a TreeSet instead of a TreeMap, you can use your comparator on one of the fields of the Animal class.

Btw, you are using reflection to get to the Id field, if the Animal baseclass contains the .getId() method, you can cast and call the method without reflection.

rsp
A: 

If you want to sort a Map by value, and the current String key is actually a property of Animal, then best way is probably to create a LinkedHashMap based on a SortedSet<Animal> or maybe a List<Animal> which is sorted using Collections#sort().

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

Only pitfall is that you have to re-sort if whenever you want to add a new Animal to the map.

BalusC