排序对象的ArrayList按字母顺序 [英] Sorting an ArrayList of Objects alphabetically
问题描述
我要创建一个排序的的ArrayList 的对象按字母顺序按电子邮件,然后打印数组排序的方法。那我有它排序它麻烦的一部分。我研究它,并使用 Collections.sort(vehiclearray)审判;
,但没有为我工作。我还是那个我需要的东西叫做比较,但无法弄清楚它是如何工作。我将不得不使用那些也可以像冒泡排序或插入排序为这种事情工作?
这是code,我到目前为止有:
公共静态无效printallsort(ArrayList的<车辆GT; vehiclearray){ ArrayList的<车辆GT; vehiclearraysort =新的ArrayList<车辆GT;();
vehiclearraysort.addAll(vehiclearray); //分类
的for(int i = 0; I< vehiclearraysort.size();我++)
如果(vehiclearray.get(ⅰ).getEmail()> vehiclearray.get第(i + 1).getEmail())//打印
对于(i = 0; I< vehiclearraysort.size();我++)
的System.out.println(vehiclearraysort.get(I)的ToString()+\\ n);}
分拣部分可以通过实现自定义完成比较<车辆与GT;
。
Collections.sort(vehiclearray,新的比较<车辆与GT;(){
公众诠释比较(车辆V1,V2车辆){
返回v1.getEmail()的compareTo(v2.getEmail())。
}
});
这个匿名类将用于其相应的电子邮件的基础上,在的ArrayList
排序车
对象按字母顺序排列。
I have to create a method that sorts an ArrayList of objects alphabetically according to email and then prints the sorted array. The part that I am having trouble with it sorting it. I have researched it and tried using Collections.sort(vehiclearray);
but that didn't work for me. I was that I needed something called a comparator but couldn't figure out how it worked. Will I have to use those or can something like bubble sort or insertion sort work for this kind of thing?
This is the code that I have so far:
public static void printallsort(ArrayList<vehicle> vehiclearray){
ArrayList<vehicle> vehiclearraysort = new ArrayList<vehicle>();
vehiclearraysort.addAll(vehiclearray);
//Sort
for(int i = 0; i < vehiclearraysort.size(); i++)
if ( vehiclearray.get(i).getEmail() > vehiclearray.get(i+1).getEmail())
//Printing
for(i = 0; i < vehiclearraysort.size(); i++)
System.out.println( vehiclearraysort.get(i).toString() + "\n");
}
The sorting part can be done by implementing a custom Comparator<Vehicle>
.
Collections.sort(vehiclearray, new Comparator<Vehicle>() {
public int compare(Vehicle v1, Vehicle v2) {
return v1.getEmail().compareTo(v2.getEmail());
}
});
This anonymous class will be used for sorting the Vehicle
objects in the ArrayList
on the base of their corresponding emails alphabetically.
这篇关于排序对象的ArrayList按字母顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!