arraylist 排序
时间: 2023-11-09 16:17:54 浏览: 85
要对 ArrayList 进行排序,你可以使用 Collections 类的 sort 方法。以下是一个示例代码:
```java
import java.util.ArrayList;
import java.util.Collections;
public class SortArrayList {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
System.out.println("Before sorting: " + numbers);
// 使用 Collections 类的 sort 方法对 ArrayList 进行排序
Collections.sort(numbers);
System.out.println("After sorting: " + numbers);
}
}
```
运行以上代码,输出将会是:
```
Before sorting: [5, 2, 8, 1]
After sorting: [1, 2, 5, 8]
```
这样,你就可以使用 `Collections.sort()` 方法对 ArrayList 进行排序了。请注意,该方法只能用于存储基本类型(如 Integer、Double 等)或实现了 Comparable 接口的类。如果你需要对自定义对象进行排序,你需要确保该对象类实现了 Comparable 接口并重写了 `compareTo()` 方法。
阅读全文
相关推荐

















