如何根据一个属性对对象数组列表进行排序? [英] How to sort an arraylist of objects based on one property?
问题描述
我有一个 Student 对象的arrayList.这些对象都有共同的属性,如姓名、UID(大学 ID 号)GPA,然后还有研究生和本科生的子类.我一直困惑于如何根据 UID 编号按从低到高的顺序对数组列表进行排序.UID 编号是 U123456 格式的字符串.总是有一个 U,然后是不同数量的整数.由于 U,我无法解析为 int 并以这种方式排序,我已经看到使用了 Comparator
类,但我不明白它,因为它似乎只比较两个对象?!如果 Comparator
类适用于此,有人可以向我解释它的作用以及它是如何工作的吗?
I have an arrayList of Student objects. The objects all have common properties such as first and last name, UID (university ID number) GPA, and then there are subclasses for graduate and undergraduate. I have been stumped as to how to sort the arraylist based on the UID number in order of lowest to highest. The UID number is a STRING in the format of U123456. There is always a U, and then a varied amount of integers. Because of the U, I cannot parse into an int and sort that way, I have seen the Comparator
class being used, but I do not understand it, as it seems to only compare two objects?! IF the Comparator
class will work for this, could someone please explain to me what it does and how it works?
推荐答案
由于这种行为,很容易进行比较:
It is easy to compare because of this behaviour:
System.out.println("u1".compareTo("u2")); // -1
System.out.println("u2".compareTo("u2")); // 0
System.out.println("u3".compareTo("u2")); // 1
System.out.println("u4".compareTo("u2")); // 2
所以这就是你需要做的:
So this is what you need to do:
- 让
Student实现Comparable
...你可以看看http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html - 在Student中定义
compareTo(Student s)
,也就是return(this.id.compareTo(s.id));
- 只需使用 ArrayList 调用 sort()
- Let
Student implement Comparable
... you can look to http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html - define
compareTo(Student s)
in Student, which is justreturn(this.id.compareTo(s.id));
- just call sort() with the ArrayList
这篇关于如何根据一个属性对对象数组列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!