Java 中根据用户需求按需排序的程序

package xdl.day16;

public class Student implements Comparable {
	private int id;
	private String name;
	private int age;

	public Student(int id, String name, int age) throws AgeExcption {
		super();
		setId(id);
		setName(name);
		setAge(age);
	}

	public Student() {
		super();
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		if (id >= 0)
			this.id = id;
		else {
			System.out.println("false");
		}
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) throws AgeExcption {
		if (age > -1 && age < 300)
			this.age = age;
		else {
			// System.out.println("年龄不合法false");
			throw new AgeExcption();
		}
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (id != other.id)
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

	@Override
	public int compareTo(Student o) {
		// TODO Auto-generated method stub
		return getId() - o.getId();
	}
}


 
  

 
  
//上面的是 Student.java 文件
package xdl.day16;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class TestSort {

	public static void main(String[] args) throws AgeExcption {
		//根据 id 排序
		Comparator c1 = new Comparator() {

			@Override
			public int compare(Student o1, Student o2) {
				// TODO Auto-generated method stub
				return o1.getId() - o2.getId();
			}
		};
		//根据名称排序
		Comparator c2 = new Comparator() {

			@Override
			public int compare(Student o1, Student o2) {
				// TODO Auto-generated method stub
				return o1.getName().compareTo(o2.getName());
			}
		};
		
		Set s1 = new TreeSet(c1);
		s1.add(new Student(9, "b", 3));
		s1.add(new Student(5, "a", 2));
		s1.add(new Student(7, "c", 3));
		for(Student m:s1){
			System.out.println(m);
		}
		
		s1 = new TreeSet(c2);
		s1.add(new Student(9, "b", 3));
		s1.add(new Student(5, "a", 2));
		s1.add(new Student(7, "c", 3));
		for(Student m:s1){
			System.out.println(m);
		}

	}

}


 
 

你可能感兴趣的:(JAVA)