Java集合操作類Collections的一些常用方法
阿新 • • 發佈:2018-12-18
public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(34); list.add(55); list.add(56); list.add(89); list.add(12); list.add(23); list.add(126); System.out.println(list); //對集合進行排序 Collections.sort(list); System.out.println(list); //對集合進行隨機排序 Collections.shuffle(list); System.out.println(list); //獲取集合最大值、最小值 int max = Collections.max(list); int min = Collections.min(list); System.out.println("Max:" + max + " Min: " + min); List<String> list2 = Arrays.asList("Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday".split(",")); System.out.println(list2); //查詢集合指定元素,返回元素所在索引 //若元素不存在,n表示該元素最有可能存在的位置索引 int index1 = Collections.binarySearch(list2, "Thursday"); int index2 = Collections.binarySearch(list2, "TTTTTT"); System.out.println(index1); int n = -index2 - 1; //查詢子串在集合中首次出現的位置 List<String> subList = Arrays.asList("Friday,Saturday".split(",")); int index3 = Collections.indexOfSubList(list2, subList); System.out.println(index3); int index4 = Collections.lastIndexOfSubList(list2, subList); System.out.println(index4); //替換集合中指定的元素,若元素存在返回true,否則返回false boolean flag = Collections.replaceAll(list2, "Sunday", "tttttt"); System.out.println(flag); System.out.println(list2); //反轉集合中的元素的順序 Collections.reverse(list2); System.out.println(list2); //交換集合中指定元素的位置 Collections.swap(list2, 0, 3); System.out.println(list2); //替換集合中的所有元素,用物件object Collections.fill(list2, "替換"); System.out.println(list2); //生成一個指定大小與內容的集合 List<String> list4 = Collections.nCopies(5, "哈哈"); System.out.println(list4); }