4 回答

TA贡献1784条经验 获得超7个赞
public static List<Dog> cloneList(List<Dog> list) { List<Dog> clone = new ArrayList<Dog>(list.size()); for (Dog item : list) clone.add(item.clone()); return clone;}
Dog
Cloneable
clone()

TA贡献1797条经验 获得超6个赞
class Dog{ public Dog() { ... } // Regular constructor public Dog(Dog dog) { // Copy all the fields of Dog. }}
public static List<Dog> cloneList(List<Dog> dogList) { List<Dog> clonedList = new ArrayList<Dog>(dogList.size()); for (Dog dog : dogList) { clonedList.add(new Dog(dog)); } return clonedList;}

TA贡献1784条经验 获得超8个赞
List<Double> original = // some listList<Double> copy = new ArrayList<Double>(original); //This does a shallow copy
clone()
考虑到与cloneable相关的所有问题,可以肯定地说,其他接口不应该扩展它,为继承而设计的类(项目17)不应该实现它。由于它的许多缺点,一些专业的程序员只是选择永远不覆盖克隆方法,从来不调用它,也许,除了复制数组。如果为继承设计类,请注意,如果选择不提供行为良好的受保护的克隆方法,子类不可能实现cloneable。
他们不依赖于一种易受风险的语言外对象创建机制。 它们并不要求对文件很少的公约进行强制执行。 它们与最终字段的正确使用没有冲突 它们不会抛出不必要的检查异常 他们不需要石膏。
HashSet s
TreeSet
new TreeSet(s)
.

TA贡献1777条经验 获得超3个赞
复制构造函数:
List<Dog> clonedDogs = dogs.stream().map(Dog::new).collect(toList());
Dog::new
Dog
克隆方法[1]:
List<Dog> clonedDogs = dogs.stream().map(d -> d.clone()).collect(toList());
得到一个 ArrayList
结果
ArrayList
ArrayList<Dog> clonedDogs = dogs.stream().map(Dog::new).collect(toCollection(ArrayList::new));
更新列表
dogs
replaceAll
dogs.replaceAll(Dog::new);
import static java.util.stream.Collectors.*;
.
收集器 ArrayList
s
ArrayList<Dog> clonedDogs = dogs.stream().map(d -> d.clone()).collect(toArrayList());public static <T> Collector<T, ?, ArrayList<T>> toArrayList() { return Collectors.toCollection(ArrayList::new);}
[1]关于 CloneNotSupportedException
:
clone
Dog
绝不能CloneNotSupportedException
map
// Note: Method is public and returns Dog, not Object @Override public Dog clone() /* Note: No throws clause here */ { ...
PS:
List<Dog> clonedDogs = dogs.stream().map(Dog::clone).collect(toList());
添加回答
举报