簡單的Java物件陣列進行排序
阿新 • • 發佈:2019-01-24
比如要對一個物件進行排序,根據他的分數來進行排序,首先要是實現Comparable介面,實現compareTo方法。
public class Person implements Comparable<Person>{ int score; String name; public Person(int score, String name) { super(); this.score = score; this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person [score=" + score + ", name=" + name + "]"; } @Override public int compareTo(Person o) { return this.score - o.score; } }
package orm_sort; import java.util.ArrayList; import java.util.Collections; import java.util.Random; public class SortTest { static ArrayList<Person> persons = new ArrayList<>(); public static void main(String[] args) { Random random = new Random(); persons.add( new Person(980, "M1")); persons.add( new Person(34, "M2")); persons.add( new Person(12, "M3")); persons.add( new Person(65, "M4")); persons.add( new Person(12, "M5")); persons.add( new Person(33, "M6")); persons.add( new Person(90, "M7")); persons.add( new Person(123, "M8")); Collections.sort(persons); for (Person person : persons) { System.out.println(person.toString());; } System.out.println(persons.get(persons.size()-1).toString()); } }
輸出結果:
Person [score=12, name=M3]
Person [score=12, name=M5]
Person [score=33, name=M6]
Person [score=34, name=M2]
Person [score=65, name=M4]
Person [score=90, name=M7]
Person [score=123, name=M8]
Person [score=980, name=M1]
Person [score=980, name=M1]
結果為從小到大排序。
如果想從大到小排序,實現compareTo方法時,用o.score -this.score即可