我们先生成20个随机数,存入ArrayList
ArrayList<Integer> al=new ArrayList<>();
Random r=new Random();
for (int i=0;i<20;i++) {
al.add(r.nextInt(100));
}
输出结果如下
对于ArrayList的排序,有两种实现形式
- 使用Collections的排序
- 使用ArrayList自带的sort()
两种方法其实大同小异
Collections的排序
这里在使用Collections中的sort()时,还要求传入一个比较器
这也很好理解,有时候我们要传入的数组内容可能不是实数,还可以是对象,这时直接调用sort的话,系统就没法知道你是想根据什么进行排序的了。
这里我们就是对整数进行排序,先自己写个比较器
class SortByIndex implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
if(o1>o2) {
return 1;
}
return -1;
}
}
然后我们传入刚刚的sort()
这样就能排序成功
ArrayList自带的排序
其实和Collection的大同小异,这里我就直接放代码
public class ArrayListTest {
public static void main(String[] args) {
ArrayList<Integer> al=new ArrayList<>();
Random r=new Random();
for (int i=0;i<20;i++) {
al.add(r.nextInt(100));
}
outputStringArrayList(al);
// Collections.sort(al,new SortByIndex());
al.sort(new SortByIndex());
System.out.println("排序后为:");
outputStringArrayList(al);
}
public static void outputArrayList(ArrayList<Integer> arr) {
Iterator<Integer> it=arr.iterator();
while(it.hasNext()) System.out.print(it.next()+" ");
System.out.println();
}
public static void outputStringArrayList(ArrayList<Integer> arr) {
String str=arr.toString();
System.out.println(str);
}
public static void outputStringLinkedList(LinkedList<Integer> ll) {
String str=ll.toString();
System.out.println(str);
}
}
class SortByIndex implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
if(o1>o2) {
return 1;
}
return -1;
}
}