开发者

Ordering Array of Objects by an attribute [duplicate]

This question already has answers here: Sort ArrayList of custom Objects by property 开发者_JS百科 (29 answers) Closed 7 years ago.

Is There a java util method, or a short way to sort an Array of some type by an attribute of that type. I currently have an array of Choice type objects where each have a getText() method that returns the visual representation of the choice. I can make a long method that creates an array of the choices texts, sort them, get their ordered index and then order the choices by that index, but I surely think there is some kind of a shortcut.

Any Suggestions?


Collections.sort(list, new Comparator<Choice>(){
 public int compare (Choise c1, Choice c2) {
   return c1.getText().compareTo(c2.getText());
 }
});

add check for null if necessary

you can move comparator to external class and use reflection to read custom field from any object. but this will make code less understandable

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜