实现list自动排序

1:实现comparable<list中的对像>接口

例:public class DataObject implements Comparable<DataObject>, Serializable {

2:重写hashcode和equals方法,重写compareTo(要比软的对像,即list中的对像)方法

例:

/**
  * 因为要按倒序排列,所以大于返回-1,等于返回0,小于返回1
  */
 public int compareTo(DataObject otherData) {
  if (this == otherData)
   return 0;
  if (otherData == null)
   return -1;
  if (this.value > otherData.value) {
   return -1;
  } else if (this.value == otherData.value) {
   return 0;
  } else {
   return 1;
  }
 }

 3:使用Collections.sort(List<DataObject >对像);// 按倒序从大到小排列

 

第二种方式(可参考:http://www.iteye.com/topic/503812

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

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

		Comparator<Person> comparator = new Comparator<Person>() {

			public int compare(Person o1, Person o2) {
				if (o1.getName() == o2.getName()) {
					return 0;
				}
				if (o1.getName() > o2.getName()) {
					return 1;
				}
				if (o1.getName() < o2.getName()) {
					return -1;
				}
				return 0;
			}

		};
        Set<Person> set = new TreeSet<Person>(comparator);
		Person p1 = new Person(1);
		Person p2 = new Person(2);
		Person p3 = new Person(3);
		Person p4 = new Person(4);
		Person p5 = new Person(5);
		Person p6 = new Person(6);
		set.add(p6);
		set.add(p3);
		set.add(p2);
		set.add(p5);
		set.add(p4);
		set.add(p1);
		for(Person p:set){
			System.out.println(p.getName());
		}
	}
}

class Person {
	public int name;

	public Person() {
	};

	public Person(int name) {
		this.name = name;
	}

	public int getName() {
		return name;
	}

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

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值