Java 简明教程

Java Collections Class

Introduction

Java Collections 类完全由对集合进行操作或返回集合的静态方法组成。下面是对集合的重要说明−

The Java Collections class consists exclusively of static methods that operate on or return collections.Following are the important points about Collections −

  1. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection.

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

Class declaration

下面是 java.util.Collections 类的声明−

Following is the declaration for java.util.Collections class −

public class Collections
   extends Object

Field

以下是 java.util.Collections 类的字段−

Following are the fields for java.util.Collections class −

  1. static List EMPTY_LIST − This is the empty list (immutable).

  2. static Map EMPTY_MAP − This is the empty map (immutable).

  3. static Set EMPTY_SET − This is the empty set (immutable).

Class methods

Methods inherited

此类从以下类中继承方法:

This class inherits methods from the following classes −

  1. java.util.Object

Adding Multiple Elements to the Collection of Integers Example

以下示例展示了 Java Collection addAll(Collection, T…​ ) 方法的使用方法,以添加一个 Integer 集合。我们使用一些整数创建了一个 List 对象,并打印了原始列表。使用 addAll(collection, T…​) 方法,我们向列表中添加了几个元素,然后打印了更新后的列表。

The following example shows the usage of Java Collection addAll(Collection,T…​ ) method to add a collection of Integers. We’ve created a List object with some integers, printed the original list. Using addAll(collection, T…​) method, we’ve added few more elements to the list and then printed the updated list.

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsDemo {

   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));

      System.out.println("Initial collection value: " + list);
      // add values to this collection
      Collections.addAll(list, 6, 7, 8);
      System.out.println("Final collection value: "+list);
   }
}

Output

让我们编译并运行上述程序,这将生成以下结果 −

Let us compile and run the above program, this will produce the following result −

Initial collection value: [1, 2, 3, 4, 5]
Final collection value: [1, 2, 3, 4, 5, 6, 7, 8]