集合对象排序

1. Collections.sort()排序

1.list集合里面存放对象person,比如要根据person对象的年龄进行排序:
利用Collections.sort()方法,重写里面的comparator方法,相当于内部类:

public class SortTest {

	public static void main(String[] args) {
		String s = "aaa";
		String string = new String("aaa");
		System.out.println("----=-----"+string==s);
		List<Student> list = new ArrayList<>();
		Student a = new Student("张三", 18);
		Student b = new Student("李四",20);
		Student c = new Student("王五",22);
		Student d = new Student("招六",21);
		list.add(a);
		list.add(b);
		list.add(c);
		list.add(d);
		System.out.println("排序前的结果:"+list);
		
		System.out.println(System.currentTimeMillis());
		Collections.sort(list, new Comparator<Student>() {

			@Override
			public int compare(Student o1, Student o2) {
				if(o1.getAge() > o2.getAge()) {
					return -1;
				}
				if(o1.getAge() == o2.getAge()) {
					return 0;
				}
				return 1;
			}
		});
		System.out.println(System.currentTimeMillis());
		System.out.println("排序后的:"+list);
		
		//如果是普通类型
		List<Integer> alist = new ArrayList<>();
		alist.add(1);
		alist.add(2);
		alist.add(5);
		alist.add(3);
		alist.add(4);
		System.out.println(alist);
		Collections.sort(alist);//升序排列
		System.out.println(alist);
		Collections.reverse(alist);
		System.out.println(alist);//降序排列
		Collections.shuffle(alist);//打乱
		System.out.println(alist);
	}
	
}
  1. 让pojo对象实现comparable接口,并且重写里面的compareTo方法:
//想根据年龄排序 需要实现comparable接口 并重写compareTo方法
public class Person implements Comparable<Person>{

	private String name;
	private int age;
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	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;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
	@Override
	public int compareTo(Person p) {
		if(this.age < p.getAge()) {
			return 1;
		}else if(this.age == p.getAge()) {
			return 0;
		}
		return -1;
	}
@Override
	public boolean equals(Object obj) {
		if(this == obj) {
			return true;
		}
		if(!(obj instanceof Student)) {
			return false;
		}
		Student s = (Student)obj;
		return this.name==s.name&&this.age==s.age;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值