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

WBOY
WBOY 转载
2023-08-24 17:49:07 405浏览

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

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

方式 #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

使用流来创建列表的副本。

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]

以上就是在Java中如何复制一个列表?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除