Comparable接口
是你要进行排序的 数据结构或者说对象 所对应的类需要实现的接口,缺点是只能按你实现的这一种方式排序:
public class UserInfo implements Comparable<UserInfo> {private int id;private String userName;private String phone;private String otherInfo;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getOtherInfo() {return otherInfo;}public void setOtherInfo(String otherInfo) {this.otherInfo = otherInfo;}@Overridepublic String toString() {return "UserInfo [id=" + id + ", userName=" + userName + ", phone=" + phone + ", otherInfo=" + otherInfo + "]";}/*** 只能按一种方式排序实现Comparable接口*/@Overridepublic int compareTo(UserInfo user) {// TODO Auto-generated method stubreturn id-user.id;}
}
public static void main(String[] args) {UserInfo[] users = new UserInfo[4];users[0] = new UserInfo();users[0].setId(15);users[0].setUserName("myr");users[1] = new UserInfo();users[1].setId(10);users[1].setUserName("zx");users[2] = new UserInfo();users[2].setId(18);users[2].setUserName("yzh");users[3] = new UserInfo();users[3].setId(8);users[3].setUserName("csm");Arrays.sort(users);//SortByName sortByName = new SortByName();//Arrays.sort(users,sortByName);for (UserInfo userInfo : users) {System.out.println(userInfo);}}
输出:按id从小到大排序
UserInfo [id=8, userName=csm, phone=null, otherInfo=null]
UserInfo [id=10, userName=zx, phone=null, otherInfo=null]
UserInfo [id=15, userName=myr, phone=null, otherInfo=null]
UserInfo [id=18, userName=yzh, phone=null, otherInfo=null]
Comparator接口
另外定义一个类实现comparator接口,然后传进去这个类是实例和要排序对象的数组这两个参数,就可以按照自己的意愿去排序:
/*** 按手机号排序* <p>Title: SortByPhone</p> * <p>Description: </p> * @author myr * @date 2019年10月25日*/
class SortByPhone implements Comparator<UserInfo>{@Overridepublic int compare(UserInfo o1, UserInfo o2) {// TODO Auto-generated method stubreturn o1.getPhone().compareTo(o2.getPhone());}}
/*** 按名字排序* <p>Title: SortByName</p> * <p>Description: </p> * @author myr * @date 2019年10月25日*/
class SortByName implements Comparator<UserInfo>{@Overridepublic int compare(UserInfo o1, UserInfo o2) {// TODO Auto-generated method stubreturn o1.getUserName().compareTo(o2.getUserName());}}
输出:按名字的字典序排序
UserInfo [id=8, userName=csm, phone=null, otherInfo=null]
UserInfo [id=15, userName=myr, phone=null, otherInfo=null]
UserInfo [id=18, userName=yzh, phone=null, otherInfo=null]
UserInfo [id=10, userName=zx, phone=null, otherInfo=null]