最简单的解决方案
只需在您的类中实现 java.lang.Comparable 接口,如下所示:
class MyStruct implements Comparable<MyStruct>{
public Boolean GUI;
public float CallTime;
public String ReqID;
public String ReqGUID;
public String Stereotype;
public String StereotypeGUID;
@Override
public int compareTo(MyStruct other) {
return ReqID.compareTo(other.ReqID);
/* also you can use ReqID.compareToIgnoreCase(other.ReqID); */
}
@Override
public String toString() {
return "(" + ReqID + ")";
}
}
也覆盖 toString() 方法仅用于打印。
另外,请记住,String 的 compareTo()方法使用字典顺序进行排序。如果您想要数字 ID,最好使用int或其他数字类型。以下是使用 Arrays.sort() 和 Collections.sort() 进行排序的完整代码 - 选择适合您的:)
public class MyStructSort {
private final static String[] STRUCT_IDS = {"C", "D", "A", "Aa", "B", "Z", "Aaa" };
private static List<MyStruct> createList() {
List<MyStruct> structList = new ArrayList<MyStruct>();
for (String id: STRUCT_IDS) {
MyStruct struct = new MyStruct();
struct.ReqID = id;
structList.add(struct);
}
return structList;
}
public static void main(String[] args) {
List<MyStruct> dataList = createList();
/* Sort using Lists (Collections) */
Collections.sort(dataList);
System.out.println("List sort:\t" + dataList);
/* Sort using arrays */
MyStruct[] dataArray = dataList.toArray(new MyStruct[dataList.size()]);
Arrays.sort(dataArray);
// print sorted array
System.out.print("Array sort:\t");
for (MyStruct struct: dataArray) {
System.out.print(struct+" ");
}
}
}
这只是演示代码,因此需要一些空值检查以及 getter 和 setter 来使其完美。