Comparable接口的使用方法--例子

1.创建Student类

package com.test.collection;

//创建Student类并实现Comparable接口,Comparable<Student>限定比较的对象为Student
public class Student implements Comparable<Student> {
	public static String school;
	private String stuName;
	private int age;
	private String major;

	public Student(String stuName, int age, String major) {

		this.stuName = stuName;
		this.age = age;
		this.major = major;
	}

	public Student() {

		// TODO Auto-generated constructor stub
	}

	public String getStuName() {
		return stuName;
	}

	public void setStuName(String stuName) {
		this.stuName = stuName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		if (age >= 18 && age <= 100) {
			this.age = age;
		} else {
			System.err.println("年龄输入非法!");
		}
	}

	public String getMajor() {
		return major;
	}

	public void setMajor(String major) {
		this.major = major;
	}

	public void sayHello() {
		System.out.println("大家好!我叫" + this.stuName + ",今年" + age + "岁了。");
	}

	// 重写toString方法
	@Override
	public String toString() {
		return "Student [stuName=" + stuName + ", age=" + age + ", major=" + major + "]";
	}

	// 因为实现了Comparable接口,必须重写compareTo方法
	@Override
	public int compareTo(Student o) {
	
		//如果被比较对象的年龄o.age大于this.age,返回1
		//如果被比较对象的年龄o.age小于this.age,返回-1
		//通过修改返回值,可以实现升序或降序排序
		if (this.age < o.age) {
			return -1;
		} else if (this.age > o.age) {
			return 1;
		}
		return 0;
	}

}

2.创建测试类TestComparable

package com.test.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestComparable {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List<Student>  stuList =new ArrayList<Student>();
		Student s1 = new Student("张三",30,"软件工程");
		Student s2 = new Student("李四",19,"软件工程");
		Student s3 = new Student("王五",40,"软件工程");
		//把s1,s2,s3三个Student实例,添加到stuList中
		stuList.add(s1);
		stuList.add(s2);
		stuList.add(s3);
		System.out.println("排序前:");
		//使用foreach遍历stuList,并调用stuList中每个对象的sayHello()方法
		for (Student s : stuList) {
			s.sayHello();
		}
		
		//使用Collections.sort排序,一个参数情况下是List实例名
		//使用此方法排序父类要实现Comparable接口并重写compareTo方法
		//通过重写compareTo方法,修改返回值,可以实现升序或降序排序
		System.out.println("升序排序后:");
		Collections.sort(stuList);
		for (Student s : stuList) {
			s.sayHello();
		}
		
	}

}

猜你喜欢

转载自blog.csdn.net/ThinkPet/article/details/81217995