对象排序Comparator与Comparable

当集合中存储的都是对象时,我们要对其进行排序,就要借助于Comparator或Comparable,以简单的方式实现对象排序或自定义排序。

例子:一个对象类:

Comparable的实现:对象类实现Comparable接口的compareTo方法


package com.chj.comparator;
public class User implements Comparable<User> {
private String username;
private Integer age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public int compareTo(User o) {
if (this.getAge() > o.getAge()) {
return 1;
} else if (this.getAge() < o.getAge()) {
return -1;
}
return 0;
}
}


Comparator的实现:创建一个比较器


package com.chj.comparator;
import java.util.Comparator;
public class MyCompatator implements Comparator<User>{
@Override
public int compare(User o1, User o2) {
if (o1.getAge() < o2.getAge()) {
return 1;
} else if (o1.getAge() > o2.getAge()) {
return -1;
}
return 0;
}
}




测试:


package com.chj;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import com.chj.comparator.MyCompatator;
import com.chj.comparator.User;


public class TestObjectSort {
public List<User> getUsers() {
List<User> list = new ArrayList<User>();
User u = new User();
u.setAge(2);
u.setUsername("derek2");
list.add(u);


u = new User();
u.setAge(1);
u.setUsername("derek1");
list.add(u);


u = new User();
u.setAge(4);
u.setUsername("derek4");
list.add(u);


u = new User();
u.setAge(3);
u.setUsername("derek3");
list.add(u);


return list;
}
public void print(List<User> list) {
for (User user : list) {
System.out.println(user.getAge() + " --- " + user.getUsername());
}
}
@Test
public void testComparator() {
List<User> list = getUsers();
print(list);
System.out.println("-------------------------------------------------");
Collections.sort(list);
print(list);
}
@Test
public void testComparable() {
List<User> list = getUsers();
print(list);
System.out.println("-------------------------------------------------");
Collections.sort(list,new MyCompatator());
print(list);
}
}

你可能感兴趣的:(对象排序Comparator与Comparable)