实现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;
	}

}

 

你可能感兴趣的:(list排序)