您好stackoverflow社区! 我是这些论坛的新手,也是Java和android编程的新手-碰巧是我的问题的对象-因此,如果有任何错误,请提前抱歉!
Hello stackoverflow community! I am new to these forums and also fairly new to java and android programming--which happen to be the objects of my question--so sorry in advance for any blunders!
我的问题是排序.我正在寻找一种根据所选字段对对象进行排序的方法(而不是根据第一个字段进行排序,然后根据下一个字段进行排序,等等,以比较器链接为例).我相信我已经找到解决问题的方法:
My issue is sorting. I am looking for a method to sort objects based on a field that I choose (not sorting based on the first field, then the next, etc. exemplified by comparator chaining). I believe I've found the solution to my problem:
stackoverflow/a/5113108/1549672
但是我很难让它正常工作.我怀疑由于缺少Java经验而可能缺少某些东西,因此欢迎您提供任何帮助!
but I am having trouble actually getting this to work. I have a suspicion that I'm probably missing something due to my lack of java experience, so any help is welcome!
这是我正在尝试的:
作为我的班级-
public class ItemLocation { String title; int id; }作为我的职责-
public void sort(final String field, List<ItemLocation> itemLocationList) { Collections.sort(itemLocationList, new Comparator<ItemLocation>() { @Override public int compare(ItemLocation o1, ItemLocation o2) { if(field.equals("title")) { return o1.titlepareTo(o2.title); } else if(field.equals("id")) { return Integer.valueOf(o1.id)pareTo(o2.id); } return 0; } }); }使用这些方法,有人可以举一个使用此方法的示例吗?我试图填充ArrayList并对其进行排序,但无济于事.
using these, could someone possibly give an example of using this method? I attempted to fill an ArrayList and sort it, but to no avail.
感谢您的帮助!
推荐答案您不应从 Comparatorpare 方法(如果它们不相等).根据合同,它是好"的,但API文档中并没有完全鼓励:
You should not return 0 from the Comparatorpare method if they are not equal. It's "okey" by the contract, but not exactly encouraged, from the API documentation:
通常是这种情况,但并非严格要求(compare(x, y)== 0)==(x.equals(y)).一般来说,任何比较器 违反此条件应清楚地表明这一事实.这 推荐的语言是注意:此比较器强加了以下命令: 与等式不一致."
It is generally the case, but not strictly required that (compare(x, y)==0) == (x.equals(y)). Generally speaking, any comparator that violates this condition should clearly indicate this fact. The recommended language is "Note: this comparator imposes orderings that are inconsistent with equals."
我认为您应该返回特定的 Comparator 而不是每个字段:
In my opinion you should return a specific Comparator for each field instead:
Comparator<ItemLocation> titleComparator = new Comparator<ItemLocation>() { @Override public int compare(ItemLocation o1, ItemLocation o2) { return o1.titlepareTo(o2.title); } } Comparator<ItemLocation> idComparator = new Comparator<ItemLocation>() { @Override public int compare(ItemLocation o1, ItemLocation o2) { return Integer.valueOf(o1.id)pareTo(o2.id); } } public void sort(final String field, List<ItemLocation> itemLocationList) { final Comparator<ItemLocation> comparator; if(field.equals("title")) { comparator = titleComparator; } else if (field.equals("id")) { comparator = idComparator; } else { throw new IllegalArgumentException("Comparator not found for " + field); } Collections.sort(itemLocationList, comparator); }