通过对象属性排序对象的ArrayList [英] Sorting ArrayList of Objects by Object attribute

查看:108
本文介绍了通过对象属性排序对象的ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象的ArrayList。这些对象有一个属性或数据类型 - 字符串''。
我需要按该字符串ArrayList中。如何实现这一目标?

I am having an Arraylist of Objects. Those object have an attribute or datatype - 'String'. I need to sort the Arraylist by that string. How to achieve this?

推荐答案

您需要编写一个<一个href=\"http://java.sun.com/javase/6/docs/api/java/util/Comparator.html\"><$c$c>Comparator<MyObject>并使用<一个href=\"http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29\"><$c$c>Collections.sort(List<T>,比较&LT ;?超级T&GT; 整理你的列表

否则,你的为MyObject 还可以的 实现可比&LT;&MyObject的GT; ,定义的自然排序的,用于比较您的具体属性,然后使用<一个href=\"http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29\"><$c$c>Collections.sort(List<T>来代替。

Or else, your MyObject can also implements Comparable<MyObject>, defining a natural ordering that compares on your specific attribute, and then use Collections.sort(List<T> instead.

  • Java Tutorials/Object Ordering

在分拣列表不同的标准:

  • Sorting an ArrayList of Contacts

比较可比

  • When to use Comparable vs Comparator
  • difference between compare() and compareTo()
  • Comparable and Comparator contract with regards to null
  • Why does the Java Collections Framework offer two different ways to sort?

这篇关于通过对象属性排序对象的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆