实现自己的Comparator及Collections详解

/**
 * 根据第一个参数小于、等于或大于第二个参数分别返回负整数、零或正整数。 
 * 总之,o1-o2是从小到大的排列。
 */
public class MyComparator implements Comparator{

	@Override
	public int compare(Person o1, Person o2) {
		int age1=o1.getAge();
		int age2=o2.getAge();
		return age1-age2;
	}

	

}
public class Person {
	private String name;
	private String address;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public int getAge() {
		return age;
	}
	public Person setAge(int age) {
		this.age = age;
		return this;
	}
	

}

public class CollectionsTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ArrayList persons=new ArrayList();
		 persons.add(new Person().setAge(1));
		 persons.add(new Person().setAge(2));
		 persons.add(new Person().setAge(3));
		 persons.add(new Person().setAge(4));
		  Collections.sort(persons,new MyComparator());
		  
		 System.out.println(persons.get(0).getAge());
		
		 

	}

}


你可能感兴趣的:(java)