简单的Java对象数组进行排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hdg745979749/article/details/79969565

比如要对一个对象进行排序,根据他的分数来进行排序,首先要是实现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即可

阅读更多

没有更多推荐了,返回首页