创建通用比较器来对树图问题进行排序
这就是我所处的位置:
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
类。关于如何解决这个问题有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
TreeMap 根据其键进行排序。地图的键是字符串。你实际上要解决什么问题?
The TreeMap is ordered in terms of its keys. The keys of your map are Strings. What problem are you actually solving?
映射基于键(而不是值)的顺序,因此这解释了为什么你有一个字符串而不是动物。
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.
你几乎就在那里,如果你使用TreeSet而不是TreeMap,你可以在Animal类的字段之一上使用你的比较器。
顺便说一句,您正在使用反射来获取 Id 字段,如果
Animal
基类包含.getId()
方法,您可以在不使用反射的情况下强制转换和调用该方法。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.如果您想按值对
Map
进行排序,并且当前的String
键实际上是Animal
的属性,那么最好的方法可能是创建基于SortedSet
的LinkedHashMap
或可能是使用Collections#sort()< 排序的
List
/代码>。唯一的陷阱是,如果您想向地图添加新的
动物
,则必须重新排序。If you want to sort a
Map
by value, and the currentString
key is actually a property ofAnimal
, then best way is probably to create aLinkedHashMap
based on aSortedSet<Animal>
or maybe aList<Animal>
which is sorted usingCollections#sort()
.Only pitfall is that you have to re-sort if whenever you want to add a new
Animal
to the map.