Collections的使用方法总结、实现原理、使用示例

目录

 

常用方法

public static boolean addAll(Collection c, T... elements):添加多个元素到集合中

public static Queue asLifoQueue(Deque deque):以Queue操作集合

public static int binarySearch(List> list, T key):返回key在链表中位置

public static int binarySearch(List list, T key, Comparator c):查找通过比较器查找对象

public static Collection checkedCollection(Collection c,Class type):可检查容器,防止错误添加元素

public static List checkedList(List list, Class type):对list添加元素的校验

public static Map checkedMap(Map m,Class keyType,Class valueType):对map的key和value检查,>,>,>

public static NavigableMap checkedNavigableMap(NavigableMap m,Class keyType,Class valueType):并行有序集合,对实现NavigableMap接口的集合的key和value排序,>,v>,v>

public static NavigableSet checkedNavigableSet(NavigableSet s,Class type):定并发实现了NavigableSet的集合的type检查

public static Queue checkedQueue(Queue queue, Class type):对实现Queue的集合type校验

public static Set checkedSet(Set s, Class type):对set的type校验

public static SortedMap checkedSortedMap(SortedMap m,Class keyType,Class valueType):对SortedMap的key和value校验,>,v>,v>

public static SortedSet checkedSortedSet(SortedSet s,Class type):对SortedSet的type校验

public static void copy(List dest, List src):将src的元素copy到dest

public static Enumeration emptyEnumeration():返回空的EmptyEnumeration

public static Iterator emptyIterator():返回空的EmptyIterator

public static final List emptyList():返回EmptyList,完全是空的

public static ListIterator emptyListIterator():返回空的EmptyListIterator

public static final Map emptyMap():返回空的EmptyMap,v>,v>

public static final NavigableMap emptyNavigableMap():返回空的EmptyNavigableMap,v>,v>

public static NavigableSet emptyNavigableSet():返回空的EmptyNavigableSet

public static final Set emptySet():返回空的EmptySet

public static final SortedMap emptySortedMap():返回空的EmptyNavigableMap,v>,v>

public static SortedSet emptySortedSet():返回空的EmptyNavigableSet

public static Enumeration enumeration(final Collection c):返回Enumeration

public static int indexOfSubList(List source, List target):子集合target在source中首次出现的位置

public static int lastIndexOfSubList(List source, List target):子集合target在source中最后出现的位置

public static ArrayList list(Enumeration e):将Enumeration转换为ArrayList

public static > T max(Collection coll):返回实现了Comparable元素集合的最大值

public static T max(Collection coll, Comparator comp):自定义比较器比较大小,找最大元素

public static > T min(Collection coll):找集合最小元素

public static T min(Collection coll, Comparator comp):自定义比较器求集合最小值

public static List nCopies(int n, T o):返回有n个元素,每个元素的值是o的列表

public static Set newSetFromMap(Map map):把map当成set操作,>

public static boolean replaceAll(List list, T oldVal, T newVal):使用new替换集合中的oldVal

public static void reverse(List list);反转list顺序(排序之后才能)

public static Comparator reverseOrder():?

public static Comparator reverseOrder(Comparator cmp) :?

public static void shuffle(List list):把集合里面的元素顺序打乱

public static void shuffle(List list, Random rnd):自定义方法打乱结合元素

public static Set singleton(T o):返回一个只包含指定对象的不可变集(太抽象,看demo)

public static List singletonList(T o):?

public static Map singletonMap(K key, V value)?,v>,v>

public static > void sort(List list):排序

public static void sort(List list, Comparator c):集合排序,自定义比较器

public static void swap(List list, int i, int j):交换i和j位置的值

public static Collection synchronizedCollection(Collection c):返回支持同步的集合

static Collection synchronizedCollection(Collection c, Object mutex):返回支持同步的集合

public static Map synchronizedMap(Map m):返回支持同步的集合,v>,v>,v>

public static NavigableMap synchronizedNavigableMap(NavigableMap m):返回支持同步的集合,v>,v>,v>

public static NavigableSet synchronizedNavigableSet(NavigableSet s) :返回支持同步的集合

public static Set synchronizedSet(Set s):返回支持同步的集合

public static SortedMap synchronizedSortedMap(SortedMap m):返回支持同步的集合,v>,v>,v>

public static SortedSet synchronizedSortedSet(SortedSet s):返回支持同步的集合

public static Collection unmodifiableCollection(Collection c):返回集合的镜像

public static List unmodifiableList(List list):返回集合的镜像

public static Map unmodifiableMap(Map m):返回集合的镜像,v>,v>

public static NavigableMap unmodifiableNavigableMap(NavigableMap m) :返回集合的镜像,>,v>,v>

public static NavigableSet unmodifiableNavigableSet(NavigableSet s) :返回集合的镜像

public static Set unmodifiableSet(Set s):返回集合的镜像

public static SortedMap unmodifiableSortedMap(SortedMap m):返回集合的镜像,>,v>,v>

public static SortedSet unmodifiableSortedSet(SortedSet s):返回集合的镜像


常用方法


public static <T> boolean addAll(Collection<? super T> c, T... elements):添加多个元素到集合中

public class Test {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        Collections.addAll(list,1,2,3,4,5);
        System.out.println(list);
    }
}

结果:

[1, 2, 3, 4, 5]

public static <T> Queue<T> asLifoQueue(Deque<T> deque):以Queue操作集合

1、Queue(队列)接口与List、Set同一级别,都是继承了Collection接口

2、实现了Deque的类有LinkedList、ArrayDeque、LinkedBlockingDeque

public class Test {
    public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList<>();
        Collections.addAll(list,1,2,3,4,5);
        Queue<Integer> queue = Collections.asLifoQueue(list);
        System.out.println(queue);
        //往队列首添加元素
        System.out.println(queue.add(6));
        System.out.println(queue);
        //往队列首添加元素
        System.out.println(queue.offer(1));
        System.out.println(queue);
        //队列首节点
        System.out.println(queue.element());
        //队列首节点
        System.out.println(queue.peek());
        System.out.println(queue);
        //获取并移除首节点
        System.out.println(queue.poll());
        System.out.println(list);
    }
}

结果:

[1, 2, 3, 4, 5]
true
[6, 1, 2, 3, 4, 5]
true
[1, 6, 1, 2, 3, 4, 5]
1
1
[1, 6, 1, 2, 3, 4, 5]
1
[6, 1, 2, 3, 4, 5]
[6, 1, 2, 3, 4, 5]

public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key):返回key在链表中位置

public class Test {
    public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList<>();
        Collections.addAll(list, 1, 2, 3, 4, 5);
        System.out.println(list);
        System.out.println(Collections.binarySearch(list, 5));
        System.out.println(list.get(4));
    }
}

结果:

[1, 2, 3, 4, 5]
4
5

public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c):查找通过比较器查找对象

实体

public class Student {
    private String name;
    private Integer age;

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "[name="+this.getName()+",age="+this.getAge()+"]";
    }
}

测试

public class Test {
    public static void main(String[] args) {
        LinkedList<Student> list = new LinkedList<>();
        list.add(new Student("刘德华",14));
        list.add(new Student("成龙",24));
        list.add(new Student("李连杰",15));
        list.add(new Student("刘亦菲",18));
        list.add(new Student("胡歌",12));

        //对排好序的列表才能二分查找
        list.sort(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getAge()-o2.getAge();
            }
        });
        System.out.println(list);
        int c = Collections.binarySearch(list, new Student("成龙", 24), new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int num = o1.getAge() - o2.getAge();
                int num1 = (num == 0 ? o1.getName().compareTo(o2.getName()) : num);
                return num1;
            }
        });
        System.out.println(c);
    }
}

结果:

[[name=胡歌,age=12], [name=刘德华,age=14], [name=李连杰,age=15], [name=刘亦菲,age=18], [name=成龙,age=24]]
4

public static <E> Collection<E> checkedCollection(Collection<E> c,Class<E> type):可检查容器,防止错误添加元素

在String类型的数组中添加Date类型,不会报错

public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        Collections.addAll(list, "1","2");
        List list2 = list;
        list2.add(new Date());
        System.out.println(list2);
        System.out.println(list);
    }
}

结果

[1, 2, Mon Jun 29 11:33:23 CST 2020]
[1, 2, Mon Jun 29 11:33:23 CST 2020]

使用checkedCollection

public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        Collections.addAll(list, "1","2");
        List list2  = (List<String>) Collections.checkedCollection(list,String.class);
        //这里这个时候就会报ClassCastException异常
        list2.add(new Date());
        System.out.println(list2);
        System.out.println(list);
    }
}

结果:

Exception in thread "main" java.lang.ClassCastException: 
java.util.Collections$CheckedCollection cannot be cast to java.util.List
	at cn.enjoyedu.ch1.Test.main(Test.java:10)

public static <E> List<E> checkedList(List<E> list, Class<E> type):对list添加元素的校验

public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        Collections.addAll(list, "1","2");
        List list2  = Collections.checkedList(list,String.class);
        //这里这个时候就会报ClassCastException异常
        list2.add(new Date());
        System.out.println(list2);
        System.out.println(list);
    }
}

结果:

Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.util.Date element into collection with element type class java.lang.String
	at java.util.Collections$CheckedCollection.typeCheck(Collections.java:3037)
	at java.util.Collections$CheckedCollection.add(Collections.java:3080)
	at cn.enjoyedu.ch1.Test.main(Test.java:12)

public static <K, V> Map<K, V> checkedMap(Map<K, V> m,Class<K> keyType,Class<V> valueType):对map的key和value检查

public class Test {
    public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put(1,"a");
        map.put(2,"b");
        map.put(3,"c");
        map.put(4,"d");
        map.put(5,5);
        //这里添加非String类型,不报错
        System.out.println(map);
        Map integerStringMap = Collections.checkedMap(map, Integer.class, String.class);
        //这里添加String类型,报错
        integerStringMap.put(6,6);
        System.out.println(map);
    }
}

结果

{1=a, 2=b, 3=c, 4=d, 5=5}
Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.lang.Integer value into map with value type class java.lang.String
	at java.util.Collections$CheckedMap.typeCheck(Collections.java:3577)
	at java.util.Collections$CheckedMap.put(Collections.java:3620)
	at cn.enjoyedu.ch1.Test.main(Test.java:23)

public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K, V> m,Class<K> keyType,Class<V> valueType):并行有序集合,对实现NavigableMap接口的集合的key和value排序

实例同上

public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s,Class<E> type):定并发实现了NavigableSet的集合的type检查

实例同上

public static <E> Queue<E> checkedQueue(Queue<E> queue, Class<E> type):对实现Queue的集合type校验

实例同上

public static <E> Set<E> checkedSet(Set<E> s, Class<E> type):对set的type校验

实例同上

public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,Class<K> keyType,Class<V> valueType):对SortedMap的key和value校验

实例同上

public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,Class<E> type):对SortedSet的type校验

实例同上

public static <T> void copy(List<? super T> dest, List<? extends T> src):将src的元素copy到dest

前提des.size>=src.size,否则会报错

public class Test {
    public static void main(String[] args) {
        List<String> soruce = new ArrayList<>();
        List<String> des = new ArrayList<>(2);
        Collections.addAll(soruce, "1","2");
        Collections.addAll(des, "a","b","c");
        Collections.copy(des,soruce);
        System.out.println(des);
        System.out.println(soruce);
    }
}

结果

public class Test {
    public static void main(String[] args) {
        List<String> soruce = new ArrayList<>();
        List<String> des = new ArrayList<>(2);
        Collections.addAll(soruce, "1","2");
        Collections.addAll(des, "a","b","c");

        System.out.println(des);
        System.out.println(soruce);

        Collections.copy(des,soruce);

        System.out.println(des);
        System.out.println(soruce);
    }
}

结果:

[a, b, c]
[1, 2]
[1, 2, c]
[1, 2]
public static boolean disjoint(Collection<?> c1, Collection<?> c2):两集合有相同元素返回false,无发挥true
public class Test {
    public static void main(String[] args) {
        List<String> soruce = new ArrayList<>();
        List<String> des = new ArrayList<>(2);
        List<String> list = new ArrayList<>(2);
        Collections.addAll(soruce, "1","2");
        Collections.addAll(list, "1","3");
        Collections.addAll(des, "a","b","c");

        System.out.println("des和soruce没有交集:"+Collections.disjoint(soruce,des));
        System.out.println("des和soruce有交集:"+Collections.disjoint(soruce,list));
    }
}

结果

des和soruce没有交集:true
des和soruce有交集:false

public static <T> Enumeration<T> emptyEnumeration():返回空的EmptyEnumeration

public class Test {
    public static void main(String[] args) {
        System.out.println(Collections.emptyEnumeration().hasMoreElements());
    }
}

结果:

false

public static <T> Iterator<T> emptyIterator():返回空的EmptyIterator

public class Test {
    public static void main(String[] args) {

        System.out.println(Collections.emptyIterator().hasNext());
    }
}

结果:

false

public static final <T> List<T> emptyList():返回EmptyList,完全是空的

返回完全是空的集合,无法进行add操作

public class Test {
    public static void main(String[] args) {
        List<Object> objects = Collections.emptyList();
        System.out.println(objects.size());
        System.out.println(objects.isEmpty());
    }
}

结果:

0
true

public static <T> ListIterator<T> emptyListIterator():返回空的EmptyListIterator

public static final <K,V> Map<K,V> emptyMap():返回空的EmptyMap

public static final <K,V> NavigableMap<K,V> emptyNavigableMap():返回空的EmptyNavigableMap

public static <E> NavigableSet<E> emptyNavigableSet():返回空的EmptyNavigableSet

public static final <T> Set<T> emptySet():返回空的EmptySet

public static final <K,V> SortedMap<K,V> emptySortedMap():返回空的EmptyNavigableMap

public static <E> SortedSet<E> emptySortedSet():返回空的EmptyNavigableSet

public static <T> Enumeration<T> enumeration(final Collection<T> c):返回Enumeration

public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(2);

        Collections.addAll(list, "1","3");
        Enumeration<String> enumeration = Collections.enumeration(list);
        while(enumeration.hasMoreElements()){
            System.out.println(enumeration.nextElement());
        }
    }
}

结果:能够迭代处理数据

1
3
public static <T> void fill(List<? super T> list, T obj):使用obj替换list中所有元素
public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(2);

        Collections.addAll(list, "1","3");
        Collections.fill(list,"test");
        System.out.println(list);
    }
}

结果:

[test, test]
public static int frequency(Collection<?> c, Object o):元素o在集合中出现的次数
public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(2);

        Collections.addAll(list, "1","3","1");

        System.out.println(Collections.frequency(list,"1"));
        System.out.println(Collections.frequency(list,"3"));
    }
}

结果:

2
1

public static int indexOfSubList(List<?> source, List<?> target):子集合target在source中首次出现的位置

public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(2);
        List<String> list2 = new ArrayList<>(2);

        Collections.addAll(list, "1","3","1","4","3","1");
        Collections.addAll(list2, "3","1");

        System.out.println(Collections.indexOfSubList(list,list2));
    }
}

结果:

1

public static int lastIndexOfSubList(List<?> source, List<?> target):子集合target在source中最后出现的位置

public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(2);
        List<String> list2 = new ArrayList<>(2);

        Collections.addAll(list, "1","3","1","4","3","1");
        Collections.addAll(list2, "3","1");

        System.out.println(Collections.lastIndexOfSubList(list,list2));
    }
}

结果:

4

public static <T> ArrayList<T> list(Enumeration<T> e):将Enumeration转换为ArrayList

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll):返回实现了Comparable元素集合的最大值

比较的对象要实现Comparable接口

public class Student implements Comparable {
    private String name;
    private Integer age;

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "[name="+this.getName()+",age="+this.getAge()+"]";
    }

    //通过年龄比较对象的大小
    @Override
    public int compareTo(Object o) {
        Student student = (Student)o;
        return this.getAge()-student.getAge();
    }
}

测试

public class Test {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        list.add(new Student("成龙",24));
        list.add(new Student("胡歌",12));
        list.add(new Student("刘亦菲",18));
        list.add(new Student("杨超越",20));

        System.out.println(list);
        Student max = Collections.max(list);
        System.out.println(max);

    }
}

结果:

[[name=成龙,age=24], [name=胡歌,age=12], [name=刘亦菲,age=18], [name=杨超越,age=20]]
[name=成龙,age=24]

public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp):自定义比较器比较大小,找最大元素

实体

public class Student{
    private String name;
    private Integer age;

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "[name="+this.getName()+",age="+this.getAge()+"]";
    }

}

测试

public class Test {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        list.add(new Student("成龙",24));
        list.add(new Student("胡歌",12));
        list.add(new Student("刘亦菲",18));
        list.add(new Student("杨超越",20));
        System.out.println(list);
        Student max = Collections.max(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getAge()-o2.getAge();
            }
        });
        System.out.println(max);

    }
}

结果

[[name=成龙,age=24], [name=胡歌,age=12], [name=刘亦菲,age=18], [name=杨超越,age=20]]
[name=成龙,age=24]

public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll):找集合最小元素

public class Student implements Comparable {
    private String name;
    private Integer age;

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "[name="+this.getName()+",age="+this.getAge()+"]";
    }

    @Override
    public int compareTo(Object o) {
        Student student = (Student)o;
        return this.getAge()-student.getAge();
    }
}

测试

public class Test {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        list.add(new Student("成龙",24));
        list.add(new Student("胡歌",12));
        list.add(new Student("刘亦菲",18));
        list.add(new Student("杨超越",20));
        System.out.println(list);
        Student min = Collections.min(list);
        System.out.println(min);
    }
}

结果:

[[name=成龙,age=24], [name=胡歌,age=12], [name=刘亦菲,age=18], [name=杨超越,age=20]]
[name=胡歌,age=12]

public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp):自定义比较器求集合最小值

public class Test {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        list.add(new Student("成龙",24));
        list.add(new Student("胡歌",12));
        list.add(new Student("刘亦菲",18));
        list.add(new Student("杨超越",20));
        System.out.println(list);
        Student min = Collections.min(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getAge()-o2.getAge();
            }
        });
        System.out.println(min);
    }
}

测试

[[name=成龙,age=24], [name=胡歌,age=12], [name=刘亦菲,age=18], [name=杨超越,age=20]]
[name=胡歌,age=12]

public static <T> List<T> nCopies(int n, T o):返回有n个元素,每个元素的值是o的列表

public class Test {
    public static void main(String[] args) {

        //返回有5个元素,每个元素的值是test的列表
        List<String> list = Collections.nCopies(5, "test");
        System.out.println(list);

    }
}

结果

[test, test, test, test, test]

public static <E> Set<E> newSetFromMap(Map<E, Boolean> map):把map当成set操作

private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(64));

通过包装ConcurrentHashMap,有了一个并发的set,类似于ConcurrentHashMap的Set

public class Test {
    public static void main(String[] args) {

         Set<String> set = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(32));
        set.add("a");
        set.add("b");
        set.add("c");
        set.add("d");
        set.add("a");
        System.out.println(set);
    }
}

结果

[a, b, c, d]

public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal):使用new替换集合中的oldVal

public class Test {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        Collections.addAll(list, 3, 1, 2, 5, 7, 6, 4, 3, 3);
        System.out.println(list);
        Collections.replaceAll(list, 3, 0);
        System.out.println(list);
    }
}

结果

[3, 1, 2, 5, 7, 6, 4, 3, 3]
[0, 1, 2, 5, 7, 6, 4, 0, 0]

public static void reverse(List<?> list);反转list顺序(排序之后才能)

public class Test {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        Collections.addAll(list, 3, 1, 2, 5, 7, 6, 4, 3, 3);
        System.out.println(list);
        //排序之后才能反向
        Collections.reverse(list);
        System.out.println(list);
        
        Collections.sort(list);
        System.out.println(list);
        
        Collections.reverse(list);
        System.out.println(list);
    }
}

结果

[3, 1, 2, 5, 7, 6, 4, 3, 3]
[3, 3, 4, 6, 7, 5, 2, 1, 3]
[1, 2, 3, 3, 3, 4, 5, 6, 7]
[7, 6, 5, 4, 3, 3, 3, 2, 1]

public static <T> Comparator<T> reverseOrder():?

public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) :?

public static void rotate(List<?> list, int distance) :把元素向后移动distance位

具体可参考Collections Rotate详解,说的比较清楚

demo1:将元素后移distance

public class Test {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        Collections.addAll(list, 3, 1, 2, 5, 7, 6, 4, 3, 3);
        System.out.println(list);
        Collections.rotate(list,2);
        System.out.println(list);

    }
}

结果:

[3, 1, 2, 5, 7, 6, 4, 3, 3]
[3, 3, 3, 1, 2, 5, 7, 6, 4]

demo2:将一个list的某个或多个元素进行移动,而不破坏其余元素的顺序(此demo来自博客https://blog.csdn.net/u013851082/article/details/71603417

public class Test {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        //把元素2向后移动两个距离,不改变原来的元素顺序
        Collections.addAll(list, 1, 2, 3, 4, 5, 6, 7);
        System.out.println(list);
        Collections.rotate(list.subList(1,list.size()-3), 2);
        System.out.println(list);

    }
}

结果:

[1, 2, 3, 4, 5, 6, 7]
[1, 3, 4, 2, 5, 6, 7]

public static void shuffle(List<?> list):把集合里面的元素顺序打乱

public class Test {
    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>();
      
        Collections.addAll(list, 1, 2, 3, 4, 5, 6, 7);
        System.out.println(list);
        Collections.shuffle(list);
        System.out.println(list);

    }
}

结果

[1, 2, 3, 4, 5, 6, 7]
[5, 4, 2, 6, 7, 1, 3]

public static void shuffle(List<?> list, Random rnd):自定义方法打乱结合元素

public class Test {
    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>();
        Collections.addAll(list, 1, 2, 3, 4, 5, 6, 7);
        System.out.println(list);
        Collections.shuffle(list,new Random(1));
        System.out.println(list);

    }
}

结果

[1, 2, 3, 4, 5, 6, 7]
[4, 1, 6, 2, 3, 7, 5]

public static <T> Set<T> singleton(T o):返回一个只包含指定对象的不可变集(太抽象,看demo)

参考:java.util.Collections.singleton()的一些理解,本demo来自于此博客

demo:移除所有值为1的元素,无法用removeAll(元素)

public class Test {
    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>();

        Collections.addAll(list, 1, 2, 3, 4, 5, 6, 1);
        System.out.println(list);

        // remove from list,只会移除第一个元素
        list.remove(1);

        // list1.removeAll("One");    这样写是不对的,因为removeAll中 需要的是Collection类型的
        System.out.println("List1 value: "+list);
        //移除所有1元素
        list.removeAll(Collections.singleton(1));
        System.out.println(list);
    }
}

结果:

[1, 2, 3, 4, 5, 6, 1]
List1 value: [1, 3, 4, 5, 6, 1]
[3, 4, 5, 6]

public static <T> List<T> singletonList(T o):?

public static <K,V> Map<K,V> singletonMap(K key, V value)?

public static <T extends Comparable<? super T>> void sort(List<T> list):排序

实体要实现Comparable

实体:

public class Student implements Comparable{
    private String name;
    private Integer age;

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "[name="+this.getName()+",age="+this.getAge()+"]";
    }

    @Override
    public int compareTo(Object o) {
        Student t = (Student)o;
        return this.getAge()-t.getAge();
    }
}

测试

public class Test {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        list.add(new Student("成龙",24));
        list.add(new Student("胡歌",12));
        list.add(new Student("刘亦菲",18));
        list.add(new Student("杨超越",20));
        System.out.println(list);
        Collections.sort(list);
        System.out.println(list);


    }
}

结果:

[[name=成龙,age=24], [name=胡歌,age=12], [name=刘亦菲,age=18], [name=杨超越,age=20]]
[[name=胡歌,age=12], [name=刘亦菲,age=18], [name=杨超越,age=20], [name=成龙,age=24]]

public static <T> void sort(List<T> list, Comparator<? super T> c):集合排序,自定义比较器

public class Test {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        list.add(new Student("成龙",24));
        list.add(new Student("胡歌",12));
        list.add(new Student("刘亦菲",18));
        list.add(new Student("杨超越",20));
        System.out.println(list);
        Collections.sort(list,new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getAge()-o2.getAge();
            }
        });
        System.out.println(list);

    }
}

结果:

[[name=成龙,age=24], [name=胡歌,age=12], [name=刘亦菲,age=18], [name=杨超越,age=20]]
[[name=胡歌,age=12], [name=刘亦菲,age=18], [name=杨超越,age=20], [name=成龙,age=24]]

public static void swap(List<?> list, int i, int j):交换i和j位置的值

public class Test {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        list.add(new Student("成龙",24));
        list.add(new Student("胡歌",12));
        list.add(new Student("刘亦菲",18));
        list.add(new Student("杨超越",20));
        System.out.println(list);
        Collections.swap(list,0,1);
        System.out.println(list);
    }
}

结果

[[name=成龙,age=24], [name=胡歌,age=12], [name=刘亦菲,age=18], [name=杨超越,age=20]]
[[name=胡歌,age=12], [name=成龙,age=24], [name=刘亦菲,age=18], [name=杨超越,age=20]]

public static <T> Collection<T> synchronizedCollection(Collection<T> c):返回支持同步的集合

参考:笔记:Collections 的 synchronized XXX方法

static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex):返回支持同步的集合

参考:笔记:Collections 的 synchronized XXX方法

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m):返回支持同步的集合

参考:笔记:Collections 的 synchronized XXX方法

public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m):返回支持同步的集合

参考:笔记:Collections 的 synchronized XXX方法

public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s) :返回支持同步的集合

参考:笔记:Collections 的 synchronized XXX方法

public static <T> Set<T> synchronizedSet(Set<T> s):返回支持同步的集合

参考:笔记:Collections 的 synchronized XXX方法

public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m):返回支持同步的集合

参考:笔记:Collections 的 synchronized XXX方法

public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s):返回支持同步的集合

参考:笔记:Collections 的 synchronized XXX方法

public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c):返回集合的镜像

特点:

1、镜像不可修改

2、对源对象的修改会体现在镜像上

public class Test {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        list.add(new Student("成龙",24));
        list.add(new Student("胡歌",12));
        list.add(new Student("刘亦菲",18));
        list.add(new Student("杨超越",20));

        System.out.println(list);
        List<Student> students = Collections.unmodifiableList(list);
        System.out.println(students);

        //这里会报错Exception in thread "main" java.lang.UnsupportedOperationException
        //students.add(new Student("杨超越",20));
        list.add(new Student("刘诗诗",20));

        //对list的修改会体现在镜像students上
        System.out.println(list);
        System.out.println(students);
    }
}

结果

[[name=成龙,age=24], [name=胡歌,age=12], [name=刘亦菲,age=18], [name=杨超越,age=20]]
[[name=成龙,age=24], [name=胡歌,age=12], [name=刘亦菲,age=18], [name=杨超越,age=20]]
[[name=成龙,age=24], [name=胡歌,age=12], [name=刘亦菲,age=18], [name=杨超越,age=20], [name=刘诗诗,age=20]]
[[name=成龙,age=24], [name=胡歌,age=12], [name=刘亦菲,age=18], [name=杨超越,age=20], [name=刘诗诗,age=20]]

 

public static <T> List<T> unmodifiableList(List<? extends T> list):返回集合的镜像

public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m):返回集合的镜像

public static <K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> m) :返回集合的镜像

public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s) :返回集合的镜像

public static <T> Set<T> unmodifiableSet(Set<? extends T> s):返回集合的镜像

public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m):返回集合的镜像

public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s):返回集合的镜像

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章