集合工具类(Collections)

2022-09-14 20:14:51 浏览数 (1)

1、Collections概述

java.util.Collections 是集合工具类,用来对集合进行操作。

2、Collections常用方法

sort()排序方法

binarySearch()二分查找方法

reverse()反转方法

shuffle()改组方法

swap()交换方法

fill()替换方法

copy()复制方法

min()最小值法

max()最大值方法

rotate()轮换方法

replaceAll()替换所有函数

代码语言:javascript复制
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsDemo {
    public static void main(String[] args) {
        System.out.println("sort");
        List list=new ArrayList<Double>();
        double array[] = {112, 111, 23, 456, 231 };
        for (int i = 0; i < array.length; i  ) {
            list.add(new Double(array[i]));
        }
        Collections.sort(list);//自然排序
        for (int i = 0; i < array.length; i  ) {
            System.out.print(list.get(i) " ");
        }
        System.out.println();

        System.out.println("shuffle");
        Collections.shuffle(list);//置换
        for (int i = 0; i < array.length; i  ) {
            System.out.print(list.get(i) " ");
        }
        System.out.println();

        Collections.sort(list);//自然排序
        System.out.println("reverse");
        Collections. reverse (list);//反转
        for (int i = 0; i < array.length; i  ) {
            System.out.print(list.get(i) " ");
        }
        System.out.println();

        Collections.sort(list);//自然排序
        System.out.println("copy");
        List li = new ArrayList();
        double arr[] = {1131,333};
        for(int j=0;j<arr.length;j  ){
            li.add(new Double(arr[j]));
        }
        Collections.copy(list,li);//拷贝
        for (int i = 0; i <list.size(); i  ) {
            System.out.print(list.get(i) " ");
        }
        System.out.println();

        System.out.println("min");
        System.out.println(Collections.min(list));//返回最小值
        System.out.println("max");
        System.out.println(Collections.max(list));//返回最大值

        System.out.println("rotate");
        Collections.rotate(list,-1);//循环
        for (int i = 0; i <list.size(); i  ) {
            System.out.print(list.get(i) " ");
        }
        System.out.println();
        System.out.println("binarySearch");
        Collections.sort(list);
        System.out.println(list);
        System.out.println(Collections.binarySearch(list, 333.0));//二分查找
    }
}

0 人点赞