Java—Collections.sort的两种排序方式

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

public class fanxing {
	public static void main(String args[]) {

		List com01 = new ArrayList();

		com01.add(new Student("10", "zhasan", 19));
		com01.add(new Student("02", "lisi", 19));
		com01.add(new Student("03", "wangwu", 19));
		com01.add(new Student("03", "wangwu", 192));
		for (Student stu : com01) {
			System.out.println(stu.getId() + "::" + stu.getName());
		}
		Collections.sort(com01);
		for (Student stu : com01) {
			System.out.println(stu.getId() + "::" + stu.getName());
		}

		List list = new ArrayList();
		list.add("aaas");
		list.add("aas");
		list.add("abas");
		list.add("zsas");
		list.add("wxas");
		System.out.println(list);
		Collections.sort(list, new StrLength());
		System.out.println(list);
	}
}

class StrLength implements Comparator {
	public int compare(String str1, String str2) {
		return str1.length() - str2.length();
	}
}

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

	Student(String id, String name, int age) {
		this.name = name;
		this.id = id;
		this.age = age;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public boolean equals(Object obj) {
		if (!(obj instanceof Student))
			return false;
		Student s = (Student) obj;
		return this.name.equals(s.name) && this.age == s.age;
	}

	public int hashCode() {
		return name.hashCode() + age * 39;
	}

	public int compareTo(Student o) {
		int Idnum = this.getId().compareTo(o.getId());
		if (Idnum == 0) {
			int namenum = this.getName().compareTo(o.getName());
			if (namenum == 0) {
				return this.getAge() - o.getAge();
			}
		}
		return Idnum;
	}
}

你可能感兴趣的:(java学习)