Java 向量的自定义排序顺序
我想根据用户定义的顺序对向量进行排序 这是我的代码片段Java 向量的自定义排序顺序,java,Java,我想根据用户定义的顺序对向量进行排序 这是我的代码片段 class xxx { private String xxName; private String xxMapName //getters and setter } // main public class Test { public static void main(String s) { List<xxx> options = new Vector<xxx>(); 场景2:(如果
class xxx {
private String xxName;
private String xxMapName
//getters and setter
}
// main
public class Test {
public static void main(String s) {
List<xxx> options = new Vector<xxx>();
场景2:(如果向量包含ISE_BASE、ISE_ADVANCED和ISE中的任意两个)
我想根据xxMapName(xxx的属性)对向量进行排序。此处的顺序应始终为
ISE\u BASE、ISE、ISE\u ADVANCED
您可以实现比较器接口并使用
Collections.sort(List<T> list, Comparator<? super T> c)
Collections.sort(列表,比较器覆盖compareTo()
xxx类实现了可比较的{
私有字符串名称;
私有字符串xxMapName
//接球手和接球手
公共国际比较(xxx obj){
if(此.xxMapName.equals(“ISE_基”)){
返回-1;
}else if(对象xxMapName.equals(“ISE_基”)){
返回1;
}else if(此.xxMapName.equals(“ISE”)){
返回-1;
}else if(对象xxMapName.equals(“ISE”)){
返回1;
}else if(此.xxMapName.equals(“ISE_ADVANCED”)){
返回-1;
}else if(对象xxMapName.equals(“ISE_ADVANCED”)){
返回1;
}
返回0;
}
}
之后,您可以使用集合。排序(选项)
嗨,rafael,谢谢您的建议。我想要所提到的精确比较逻辑scenarios@SatishCh我已经更新了答案。请检查。按ISE_基本、ISE、ISE_高级排序。
xxx x1 = new xxx();
x1.setXxName("s1");
x1.setXxMapName("ISE_BASE");
options.add(x1);
xxx x2 = new xxx();
x2.setXxName("s1");
x2.setXxMapName("ISE_ADVANCED");
options.add(x2);
}
}
Collections.sort(List<T> list, Comparator<? super T> c)
class xxx implements Comparable<xxx> {
private String xxName;
private String xxMapName
//getters and setter
public int compareTo(xxx obj) {
if (this.xxMapName.equals("ISE_BASE")) {
return -1;
} else if (obj.xxMapName.equals("ISE_BASE")) {
return 1;
} else if (this.xxMapName.equals("ISE")) {
return -1;
} else if (obj.xxMapName.equals("ISE")) {
return 1;
} else if (this.xxMapName.equals("ISE_ADVANCED")) {
return -1;
} else if (obj.xxMapName.equals("ISE_ADVANCED")) {
return 1;
}
return 0;
}
}