Collections工具類
- 1. 常用的 Collections 方法
- 2. 代碼示例
??Java中的 Collections
工具類提供了一系列靜態方法,用于對集合進行各種操作,如排序
、查找
、替換
等。下面我們來看一些 Collections 工具類中常用的API和使用示例。
1. 常用的 Collections 方法
- sort(List list) : 對List集合進行升序排序。
- reverse(List<?> list) : 反轉List集合中的元素順序。
- shuffle(List<?> list) : 隨機打亂List集合中的元素順序。
- binarySearch(List<? extends Comparable<? super T>> list, T key) : 使用二分查找算法在已排序的List中查找指定元素。
- replaceAll(List list, T oldVal, T newVal) : 將List中所有等于 oldVal 的元素替換為 newVal 。
2. 代碼示例
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;public class CollectionsExample {public static void main(String[] args) {List<Integer> numbers = new ArrayList<>();numbers.add(5);numbers.add(2);numbers.add(8);numbers.add(1);numbers.add(3);// 排序Collections.sort(numbers);System.out.println("numbers: " + numbers);// 反轉Collections.reverse(numbers);System.out.println("numbers: " + numbers);// 隨機打亂順序Collections.shuffle(numbers);System.out.println("numbers: " + numbers);// 二分查找int key = 2;int index = Collections.binarySearch(numbers, key);System.out.println("index of " + key + ": " + index);// 替換元素Collections.replaceAll(numbers, 3, 10);System.out.println("numbers: " + numbers);}
}
在上面的代碼中,我們創建了一個ArrayList集合并使用 Collections 工具類中的方法對其進行排序、反轉、打亂順序、二分查找以及替換元素的操作。
上一篇 Java中List、Set、Map三種集合之間的區別 | 記得點贊收藏哦!!! | 下一篇 Java中Comparable和Comparator實現排序的使用與區別。 |