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):返回集合的鏡像

 

 

 

 

 

 

 

 

 

 

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