java中怎样克隆,如何在Java中克隆列表?

要克隆Java中的列表,最简单的方法是使用ArrayList.clone()方法-

示例import java.util.ArrayList;

public class Demo {

public static void main(String args[]) {

// create an empty array list

ArrayList arrlist1 = new ArrayList();

// use add for new value

arrlist1.add(new StringBuilder("Learning-"));

// using clone to affect the objects pointed to by the references.

ArrayList arrlist2 = (ArrayList) arrlist1.clone();

// appending the string

StringBuilder strbuilder = arrlist1.get(0);

strbuilder.append("list1, list2-both pointing to the same StringBuilder");

System.out.println("The 1st list prints: ");

// both lists will print the same value, printing list1

for (int i = 0; i 

System.out.print(arrlist1.get(i) + " ");

}

System.out.println("\nThe 2nd list prints the same i.e:");

// both lists will print the same value, printing list2

for (int i = 0; i 

System.out.print(arrlist2.get(i));

}

}

}

输出结果The 1st list prints:

Learning-list1, list2-both pointing to the same StringBuilder

The 2nd list prints the same i.e:

Learning-list1, list2-both pointing to the same StringBuilder

示例

让我们看另一个在Java中克隆列表的例子-import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;

public class Example {

public static void main(String[] args) {

List myList = Arrays.asList("Welcome", "to", "the", "website");

System.out.print("Initial List = "+myList);

List newList = myList.stream().collect(Collectors.toList());

}

}

输出结果Initial List = [Welcome, to, the, website]

Cloned List = [Welcome, to, the, website]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值