Java中的Collections类– java.util.Collections

晁英彦
2023-12-01

Collections class in java is a useful utility class to work with collections in java. The java.util.Collections class directly extends the Object class and exclusively consists of the static methods that operate on Collections or return them.

Java中的Collections类是一个有用的实用程序类,可以与java中的集合一起使用java.util.Collections类直接扩展Object类,并且专门由对Collections进行操作或将其返回的静态方法组成。

Java中的Collections类 (Collections Class in java)

Collections class contains polymorphic algorithms that operate on collections and “wrappers” — which return a new collection backed by a specified collection. It is a member of Java Collections Framework.

Collections类包含对集合和“包装器”进行操作的多态算法,这些算法返回由指定集合支持的新集合。 它是Java Collections Framework的成员。

The documentation for the polymorphic algorithms included in this class generally includes a brief description of the implementation which is regarded as the implementation notes, rather than parts of the specification.

此类中包含的多态算法文档通常包括对实现的简要说明,该描述被视为实现说明,而不是规范的一部分。

While implementing these methods, we can substitute with other algorithms, so long as the specification itself is adhered to. For example, the algorithm used by Collections.sort() does not have to be a mergesort, but it does have to be stable.

在实现这些方法时,只要遵守规范本身,我们就可以用其他算法代替。 例如, Collections.sort()使用的算法不必是mergesort,但必​​须稳定。

集合类字段 (Collections class fields)

Collections class contains 3 fields: EMPTY_LIST, EMPTY_SET, EMPTY_MAP, which can be used to get immutable empty List, Map and Set respectively.

Collections类包含3个字段: EMPTY_LISTEMPTY_SETEMPTY_MAP ,它们可以分别用于获取不可变的空ListMapSet

集合类方法 (Collection class methods)

Let’s take an example collection and walk through different methods provided by Collections class in java.

让我们以一个示例集合为例,并逐步介绍一下Java中Collections类提供的不同方法。

  1. boolean addAll(Collection c, T... elements): This method adds all of the provided elements to the specified collection at once. The elements can be provided as a comma-separated list.
    List fruits = new ArrayList();
    Collections.addAll(fruits, "Apples", "Oranges", "Banana");
    fruits.forEach(System.out::println);

    The output for this will be:

    boolean addAll(Collection c, T... elements) :此方法将所有提供的元素立即添加到指定的collection中。 可以将这些元素提供为以逗号分隔的列表。
    List fruits = new ArrayList();
    Collections.addAll(fruits, "Apples", "Oranges", "Banana");
    fruits.forEach(System.out::println);

    输出为:

  2. void sort(List list, Comparator c): This method sorts the provided list according to the natural ordering. We can also pass in s Comparator, if we want some custom ordering.
    Collections.sort(fruits);
    System.out.println("Sorted according to natural ordering:");
    fruits.forEach(System.out::println);
    
    Collections.sort(fruits, Comparator.reverseOrder());
    System.out.println("Sorted according to reverse of natural ordering:");
    fruits.forEach(System.out::println);

    Output:

    void sort(List list, Comparator c) :此方法根据自然顺序对提供的列表进行排序。 如果我们需要一些自定义顺序,我们也可以传入s Comparator
    Collections.sort(fruits);
    System.out.println("Sorted according to natural ordering:");
    fruits.forEach(System.out::println);
    
    Collections.sort(fruits, Comparator.reverseOrder());
    System.out.println("Sorted according to reverse of natural ordering:");
    fruits.forEach(System.out::println);

    输出:

  3. Queue asLifoQueue(Deque deque): This method returns a view of Deque as a Last-in-first-out (Lifo) Queue.
    The methods add and remove are mapped to push, pop respectively and so on. This can be useful when we would like to use a method requiring a Queue but we need Lifo ordering.
    Deque deque = new LinkedList();
    deque.addFirst("Apples");
    deque.add("Oranges");
    deque.addLast("Bananas");
    
    Queue queue = Collections.asLifoQueue(deque);
    System.out.println(queue.poll());
    System.out.println(queue.poll());
    System.out.println(queue.poll());

    Output:

    Queue asLifoQueue(Deque deque) :此方法将Deque的视图作为Queue asLifoQueue(Deque deque)先出(Lifo) Queue
    add和remove方法分别映射为push,pop等。 当我们想使用需要Queue但需要Lifo排序的方法时,这很有用。
    Deque deque = new LinkedList();
    deque.addFirst("Apples");
    deque.add("Oranges");
    deque.addLast("Bananas");
    
    Queue queue = Collections.asLifoQueue(deque);
    System.out.println(queue.poll());
    System.out.println(queue.poll());
    System.out.println(queue.poll());

    输出:

  4. int binarySearch(List<? extends Comparable> list, T key): This method searches the key using binary search in the specified list. The list should be sorted by natural ordering, before calling this method, otherwise, the result will be undefined.

    It returns the index of the element in the sorted list if the element is found, in other cases, it returns (-(insertion point)-1). Where, the insertion point is defined as the point at which the key would be inserted into the list, i.e. the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key.
    Note that this guarantees that the return value will be >= 0 if the key is found.

    Collections.sort(fruits);
    System.out.println(Collections.binarySearch(fruits, "Banana"));
    System.out.println(Collections.binarySearch(fruits, "Grapes"));

    The output:

    We can also pass in a Comparator, which indicates that the list is sorted in the order induced by the specified comparator

    int binarySearch(List<? extends Comparable> list, T key) :此方法在指定列表中使用二进制搜索来搜索键。 在调用此方法之前,应按自然顺序对列表进行排序,否则结果将不确定。

    如果找到该元素,它将返回该元素在排序列表中的索引,在其他情况下,它将返回(-(插入点)-1)。 其中,插入点定义为将键插入列表的点,即,第一个元素的索引大于键的索引;如果列表中的所有元素均小于指定的元素,则为list.size()键。
    请注意,这保证了如果找到密钥,返回值将> = 0。

    Collections.sort(fruits);
    System.out.println(Collections.binarySearch(fruits, "Banana"));
    System.out.println(Collections.binarySearch(fruits, "Grapes"));

    输出:

    我们还可以传入一个Comparator ,它表示列表是按指定比较器所诱导的顺序排序的

  5. Collection checkedCollection(Collection c, Class type): This method provides a dynamically typesafe view of the provided collection. It is useful to keep an eye on the collection, that any wrongly typed element is not inserted in it.
    List list = new ArrayList();
    Collections.addAll(list, "one", "two", "three", "four");
    Collection checkedList = Collections.checkedCollection(list, String.class);
    System.out.println("Checked list content: " + checkedList);
    //we can add any type of element to list
    list.add(10);
    //we cannot add any type of elements to chkList, doing so
    //throws ClassCastException
    checkedList.add(10);

    Output:

    Similarly, we have check methods for specific collections such as List, Map, Set, etc.

    Collection checkedCollection(Collection c, Class type) :此方法提供所提供集合的动态类型安全视图。 注意集合,不要在其中插入任何错误键入的元素,这很有用。
    List list = new ArrayList();
    Collections.addAll(list, "one", "two", "three", "four");
    Collection checkedList = Collections.checkedCollection(list, String.class);
    System.out.println("Checked list content: " + checkedList);
    //we can add any type of element to list
    list.add(10);
    //we cannot add any type of elements to chkList, doing so
    //throws ClassCastException
    checkedList.add(10);

    输出:

    同样,我们为特定集合(例如ListMapSet等)提供检查方法。

  6. void copy(List dest, List src): This method copies all of the elements from source list to destination list. After this operation is performed, the index of each copied element in the destination list will be identical to its index in the source list.

    In the previous method example, we created a list which contains 5 elements. Let’s copy out “fruits” list to this list and see what happens:

    Collections.copy(list, fruits);
    list.forEach(System.out::println);

    The output will be:

    The destination list must be at least as long as the source list. In our example, it is longer than the source list, so in this case, the remaining elements in the destination list are unaffected (here, “four” and “10”).

    void copy(List dest, List src) :此方法将所有元素从源列表复制到目标列表。 执行此操作后,目标列表中每个复制元素的索引将与源列表中其索引相同。

    在前面的方法示例中,我们创建了一个包含5个元素的列表。 让我们将“水果”列表复制到此列表中,看看会发生什么:

    Collections.copy(list, fruits);
    list.forEach(System.out::println);

    输出将是:

    目标列表必须至少与源列表一样长。 在我们的示例中,它比源列表长,因此在这种情况下,目标列表中的其余元素不受影响(此处为“四个”和“ 10”)。

  7. boolean disjoint(Collection c1, Collection c2): This method returns true if the two specified collections have no elements in common.

    In the previous example we copied the fruits to list, so now they are not disjoint. So, when we execute:

    System.out.println(Collections.disjoint(list, fruits));

    The output will be:

    Let’s create another list for “vegetables” and check if it is disjoint to “fruits”.

    List vegetables = new ArrayList();
    Collections.addAll(vegetables, "Potato", "Cabbage");
    System.out.println(Collections.disjoint(vegetables, fruits));

    The output is:

    If we pass a same collection in both arguments, we get false, unless they are empty:

    System.out.println(Collections.disjoint(vegetables, vegetables));
    System.out.println(Collections.disjoint(new ArrayList(), new ArrayList()));

    Output:

    boolean disjoint(Collection c1, Collection c2) :如果两个指定的集合没有共同的元素,则此方法返回true。

    在前面的示例中,我们将水果复制到列表中,因此现在它们不脱节了。 因此,当我们执行时:

    System.out.println(Collections.disjoint(list, fruits));

    输出将是:

    让我们为“蔬菜”创建另一个列表,并检查它是否与“水果”不相交。

    List vegetables = new ArrayList();
    Collections.addAll(vegetables, "Potato", "Cabbage");
    System.out.println(Collections.disjoint(vegetables, fruits));

    输出为:

    如果我们在两个参数中传递相同的集合,则除非它们为空,否则将返回false:

    System.out.println(Collections.disjoint(vegetables, vegetables));
    System.out.println(Collections.disjoint(new ArrayList(), new ArrayList()));

    输出:

  8. void fill(List list, T obj): This method replaces all of the elements of the specified list with the specified element.
    If we fill our “list” list, all its five elements will be replaced:
    Collections.fill(list, "filled with dummy data");
    list.forEach(System.out::println);

    Output:

    void fill(List list, T obj) :此方法将指定列表的所有元素替换为指定元素。
    如果我们填写“列表”列表,则将替换其所有五个元素:
    Collections.fill(list, "filled with dummy data");
    list.forEach(System.out::println);

    输出:

  9. int frequency(Collection c, Object o): This method returns the number of elements in the specified collection which are equal to the specified object.

    From our previous example, if we say:

    System.out.println(Collections.frequency(list, "filled with dummy data"));

    It returns :

    int frequency(Collection c, Object o) :此方法返回指定集合中等于指定对象的元素数。

    从前面的示例中,如果我们说:

    System.out.println(Collections.frequency(list, "filled with dummy data"));

    它返回:

  10. int indexOfSubList(List source, List target): This method returns the starting position of the first occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.

    For example, if we create a sublist for our “fruit” list:

    List fruitsSubList1 = new ArrayList();
    Collections.addAll(fruitsSubList1, "Oranges", "Banana");
    System.out.println(Collections.indexOfSubList(fruits, fruitsSubList1));

    We get the ourput:

    Because this sublist starts from index 1 of fruits.
    Now, if we try to do the same for another sublist that does not exist:

    List fruitsSubList2 = new ArrayList();
    Collections.addAll(fruitsSubList2, "Kiwi", "Pinapple");
    System.out.println(Collections.indexOfSubList(fruits, fruitsSubList2));

    We get:

    Also note that if the size of sublist > size of the list, we get -1.
    We have another method int lastIndexOfSubList(List source, List target), that just returns the last index for the specified sublist, otherwise, produces same output as this one.

    int indexOfSubList(List source, List target) :此方法返回指定目标列表在指定源列表中首次出现的起始位置,如果没有出现,则返回-1。

    例如,如果我们为“水果”列表创建一个子列表:

    List fruitsSubList1 = new ArrayList();
    Collections.addAll(fruitsSubList1, "Oranges", "Banana");
    System.out.println(Collections.indexOfSubList(fruits, fruitsSubList1));

    我们得到我们的结论:

    因为此子列表从水果的索引1开始。
    现在,如果我们尝试对另一个不存在的子列表执行相同的操作:

    List fruitsSubList2 = new ArrayList();
    Collections.addAll(fruitsSubList2, "Kiwi", "Pinapple");
    System.out.println(Collections.indexOfSubList(fruits, fruitsSubList2));

    我们得到:

    还要注意,如果子列表的大小>列表的大小,则得到-1。
    我们还有另一个方法int lastIndexOfSubList(List source, List target) ,该方法只返回指定子列表的最后一个索引,否则将产生与此相同的输出。

  11. static ArrayList list(Enumeration e) and Enumeration enumeration(Collection c): These methods returns an array list from enumeration and an enumeration from a collection, respectively, so as to provide interoperability between legacy APIs that return enumerations and new APIs that require collections.

    static ArrayList list(Enumeration e)Enumeration enumeration(Collection c) :这些方法分别从枚举返回数组列表和从集合返回枚举,以便在返回枚举的旧式API与需要集合的新API之间提供互操作性。
  12. T max(Collection coll, Comparator comp): This method returns the maximum element in collection according to the natural ordering of elements.
    System.out.println(Collections.max(fruits));

    Output:

    We can also pass the Comparator inside this method if we want a custom ordering.
    Similarly min method is also available, which can also be used with or without the Comparator.

    T max(Collection coll, Comparator comp) :此方法根据元素的自然顺序返回collection中的最大元素。
    System.out.println(Collections.max(fruits));

    输出:

    如果我们要自定义排序,也可以在此方法内传递Comparator
    同样,也可以使用min方法,无论有没有Comparator ,都可以使用它。

  13. Collection<T> synchronizedCollection(Collection<T> c): This method returns a synchronized (thread-safe) collection backed by the provided collection. It’s convinient to get synchronized collections from any collection object as and when required. API also provides us with synchronizedList method which returns thread-safe list backed by provided list in the argument.
    Collection<String> synchronizedCollection = 
      Collections.synchronizedCollection(fruits);
    List<String> synchronizedList = Collections.synchronizedList(fruits);

    Also, There are synchronizedMap, synchronizedSet, synchronizedSortedSet as well as synchronizedSortedMap methods available which do the similar job.

    Collection<T> synchronizedCollection(Collection<T> c) :此方法返回由提供的集合支持的同步(线程安全)集合。 在需要时从任何集合对象中获取同步集合是很方便的。 API还为我们提供了synchronizedList方法,该方法返回由参数中提供的列表支持的线程安全列表。

    另外,还有可用的synchronizedMapsynchronizedSetsynchronizedSortedSet以及synchronizedSortedMap方法可以完成类似的工作。

These are the frequently used methods, apart from which we also have other methods like newSetFromMap, replaceAll, swap, reverse, etc.

这些是常用的方法,除此之外,我们还有其他方法,例如newSetFromMapreplaceAllswapreverse等。

Note that all the methods of this class throw a NullPointerException if the collections or class objects provided to them are null.

请注意,如果提供给它们的集合或类对象为null,则此类的所有方法都将引发NullPointerException

The “destructive” algorithms — algorithms that modify the collection on which they operate, contained in this class, are specified to throw UnsupportedOperationException if the collection does not support the appropriate mutation primitives.

“破坏性”算法-修改此类所包含的操作的算法,包含在此类中,如果该集合不支持适当的变异原语,则将其引发UnsupportedOperationException

Also, these algorithms may, or may not throw this exception if an invocation would have no effect on the collection. For example, invoking the sort method on an unmodifiable list that is already sorted may or may not throw UnsupportedOperationException.

同样,如果调用对集合没有影响,这些算法可能会抛出异常,也可能不会抛出此异常。 例如,在已排序的不可修改列表上调用sort方法可能会或可能不会抛出UnsupportedOperationException

That’s all for the Collections class.

这就是Collections类的全部内容。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/16635/collections-class-java-util-collections

 类似资料: