Comparableインタフェースの使用方法--例


1.Studioクラスの作成
package com.test.collection;

//  Student    Comparable  ,Comparable        Student
public class Student implements Comparable {
	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  stuList =new ArrayList();
		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();
		}
		
	}

}