现在有个需求是这样的,应用列表需要排序,优先级 打开=》安装=》其他
效果如下
现在来模拟此实现一个demo
关键类StatusComparator,实现自定义排序规则,这里要注意的是状态是一个常量类,而且是前期版本已经建好,所以不能投机取巧直接更改常量类的int值来比较。这里选择了根据类型来判断
public class StatusComparator implements Comparator<DownloadInfo> {
@Override
public int compare(DownloadInfo o1, DownloadInfo o2) {
int status1 = o1.getStatus();
int status2 = o2.getStatus();
switch (status1) {
case InstallState.installComplete:
if (status2 == InstallState.installComplete) {
return 0;
}
return -1;
case InstallState.install:
if (status2 == InstallState.installComplete) {
return 1;
}
if(status2 == InstallState.install) {
return 0;
}
return -1;
default:
if (status2 == InstallState.installComplete || status2 == InstallState.install) {
return 1;
}
return 0;
}
}
}
测试类TestComparator
public class TestComparator {
public static void main(String[] args) {
DownloadInfo downloadInfo1 = new DownloadInfo("王者荣耀",InstallState.install);
DownloadInfo downloadInfo2 = new DownloadInfo("连连看",InstallState.installFail);
DownloadInfo downloadInfo3 = new DownloadInfo("全民超神",InstallState.installing);
DownloadInfo downloadInfo4 = new DownloadInfo("炉石传说",InstallState.installComplete);
DownloadInfo downloadInfo5 = new DownloadInfo("三国杀",InstallState.install);
List<DownloadInfo> downloadInfoList = new ArrayList<>();
downloadInfoList.add(downloadInfo1);
downloadInfoList.add(downloadInfo2);
downloadInfoList.add(downloadInfo3);
downloadInfoList.add(downloadInfo4);
downloadInfoList.add(downloadInfo5);
System.out.println("sort前==============");
for (int i = 0; i < downloadInfoList.size(); i++) {
System.out.print(downloadInfoList.get(i).getName()+"\t");
}
System.out.println("\nsort后============");
Collections.sort(downloadInfoList,new StatusComparator());
//since 1.8+
//downloadInfoList.sort(new StatusComparator());
for (int i = 0; i < downloadInfoList.size(); i++) {
System.out.print(downloadInfoList.get(i).getName()+"\t");
}
}
}
亲测,结果可靠
sort前==============
王者荣耀 连连看 全民超神 炉石传说 三国杀
sort后============
炉石传说 王者荣耀 三国杀 连连看 全民超神
其他相关类
下载类DownloadInfo
public class DownloadInfo {
private String name;
private int status;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DownloadInfo(String name) {
this.name = name;
}
public DownloadInfo(String name, int status) {
this.name = name;
this.status = status;
}
@Override
public String toString() {
return "DownloadInfo{" +
"name='" + name + '\'' +
", status=" + status +
'}';
}
}
安装状态InstallState
public class InstallState {
//等待安装
public final static int install = 11;
//安装完成
public final static int installComplete = 12;
//安装失败
public final static int installFail = 13;
//升级
public final static int upgrade = 14;
//忽略升级
public final static int ignore_upgrade = 15;
//安装中
public final static int installing = 16;
}