首页 > 文章列表 > 在Java中如何复制一个列表?

在Java中如何复制一个列表?

java 列表 复制 复制列表的关键词:
184 2023-08-19

通过多种方式可以将元素列表复制到另一个列表中。

方式 #1

通过将另一个列表作为构造函数参数创建一个列表。

List<String> copyOflist = new ArrayList<>(list);

创建一个列表,并使用addAll方法将源列表的所有元素添加到其中。

方式 #2

List<String> copyOfList = new ArrayList<>();
copyOfList.addAll(list);

方法 #3

使用 Collections.copy 方法将源列表的内容复制到目标列表。如果存在索引,则现有元素将被覆盖。

Collections.copy(copyOfList, list);

Way #4

Use Streams to create a copy of a list.

List<String> copyOfList = list.stream().collect(Collectors.toList());

Example

以下是一个示例,用于解释使用多种方法创建List对象的副本。

package com.tutorialspoint;

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

public class CollectionsDemo {
   public static void main(String[] args) {
      List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
      System.out.println("Source: " + list);
      List<Integer> copyOfList1 = new ArrayList<>(list);
      System.out.println("Copy 1: " + copyOfList1);
      List<Integer> copyOfList2 = new ArrayList<>();
      copyOfList2.addAll(list);
      System.out.println("Copy 2: " + copyOfList2);
      List<Integer> copyOfList3 = Arrays.asList(6, 7, 8, 9, 0 );
      Collections.copy(copyOfList3, list);
      System.out.println("Copy 3: " + copyOfList3);
      List<Integer> copyOfList4 = list.stream().collect(Collectors.toList());
      System.out.println("Copy 4: " + copyOfList4);
   }
}

输出

这将产生以下结果 −

Source: [1, 2, 3, 4, 5]
Copy 1: [1, 2, 3, 4, 5]
Copy 2: [1, 2, 3, 4, 5]
Copy 3: [1, 2, 3, 4, 5]
Copy 4: [1, 2, 3, 4, 5]