Comparable和Comparator的使用(自定義對類的比較)

如果我們有一個List<User> 裏面存放user1,user2,user3,我們使用Collections.sort(list)排序是實現不了效果的。

像List<String>字符串list可以實現,是因爲String對象已經實現了Comparable接口。

所以User想要實現排序,也需要實現Compa

public class UserWithCompare implements Comparable{
	private String name;
	private int age;
	private String job;
	private int tel;
	private String address;
	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;
	}
	public String getJob() {
		return job;
	}
	public void setJob(String job) {
		this.job = job;
	}
	public int getTel() {
		return tel;
	}
	public void setTel(int tel) {
		this.tel = tel;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	@Override
	public int compareTo(Object o) {
		if(this == o){
			return 0;
		}else if(o!=null && o instanceof UserWithCompare){
			UserWithCompare u = (UserWithCompare) o;
			int i = name.compareTo(u.getName());
			if(i == 0){
				i = age - u.getAge();
				if(i == 0){
					return tel - u.getTel();
				}else{
					return i;
				}
			}else{
				return i;
			}
		}
		return -1;
	}
	@Override
	public String toString() {
		return "UserWithCompare [name=" + name + ", age=" + age + ", job="
				+ job + ", tel=" + tel + ", address=" + address + "]";
	}
}

這樣的UserWithCompare類就可以使用Collections.sort(list)來實現排序。



如果程序設計之初沒有實現Comparable接口,後續開發中還可以使用排序麼?

當然可以,可以實現Comparator接口來補。具體實現方法:

Collections.sort(list,new Comparator<UserWithoutCompare>(){

			@Override
			public int compare(UserWithoutCompare o1, UserWithoutCompare o2) {
				// TODO Auto-generated method stub
				return o1.getName().compareTo(o2.getName());
			}
			
		});
發佈了21 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章