Collections.sort 重写compare()方法

Comparator是个接口,主要比的是两个对象,比较规则是自己写的,可以重写他的compare()和equals()这两个方法,也就是说比较的方法。如果是Null的话,就是使用元素的自然顺序,如1 3 2 4就是1 2 3 4 。字母也可以compare(a,b)方法:根据第一个参数小于、等于或大于第二个参数分别返回负整数、零或正整数。

Test.java

package com.djcken;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.djcken.UserBean.ComparatorUser;

public class Test 
{
	public static void main(String[] args){             
	
		List userlist=new ArrayList();             
		  userlist.add(new UserBean("d","1"));             
		  userlist.add(new UserBean("a","4"));             
		  userlist.add(new UserBean("e","5"));             
		  userlist.add(new UserBean("b","2"));               
		  userlist.add(new UserBean("f","5"));             
		  userlist.add(new UserBean("c","3"));             
		  userlist.add(new UserBean("g","6"));             
		               
		  ComparatorUser comparator= new ComparatorUser();         
		  Collections.sort(userlist, comparator);             
		                
		  for (int i=0;i<userlist.size();i++){             
			  UserBean user_temp=(UserBean)userlist.get(i);             
		      System.out.println(user_temp.getAge()+","+user_temp.getName());              
		  }                 
		 }             
}

UserBean.java

package com.djcken;

import java.util.Comparator;

public class UserBean
{
	private String age;
	private String name;
	
	public UserBean(String age, String name) {
		super();
		this.age = age;
		this.name = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public static class ComparatorUser implements Comparator{

		public int compare(Object o1, Object o2) {
			UserBean user0 = (UserBean) o1;
			UserBean user1 = (UserBean) o2;
			int thislv = user0.getAge().compareTo(user1.getAge());
			if (thislv == 0) {
				return user0.getName().compareTo(user1.getName());
			} else {
				return thislv;
			}
		}
	} 
}

结果:

1,d
2,b
3,c
4,a
5,e
5,f
6,g



你可能感兴趣的:(String,object,list,user,equals,Class)