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<Student> com01 = new ArrayList<Student>();

		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<String> list = new ArrayList<String>();
		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<String> {
	public int compare(String str1, String str2) {
		return str1.length() - str2.length();
	}
}

class Student implements Comparable<Student> {
	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;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值