Generics, Copy Constructor, Clone method

I am trying to create a shared container that has an instance constructor. I am having problems using the clone method, although I encoded it. Here is what I still have:

public class MyBox<T> { private List<T> list; public MyBox() { list = new ArrayList<T>(); } public void add(T item ) { list.add(item); } public MyBox(MyBox<T> other) throws CloneNotSupportedException //this is giving me trouble { for(T item : other.list) { list.add((T) item.clone()); } } } 

How can I make my copy constructor work?

+4
source share
4 answers

Usually you do not need to clone an item.

 public MyBox(MyBox<T> other) { list = new ArrayList<T>(other.list); } 

When you add an item from collection A to collection B, the item now refers to both two collections A and B.

+3
source

What about the limitations common to Clonable, he is sure that cloning of the elements will be allowed:

 public class MyBox<T extends Clonable> { ... 
0
source
 public MyBox(MyBox<T> other) { this.list = new ArrayList<T>(other.getList()); } 

but you must first add a getter for your list in this case.

UPD it makes a shallow copy.

0
source

Unfortunately, in Java there is no general way to clone an object. Some classes have a public clone() method that allows you to clone, but there is no common superclass or interface to the public clone() method. (Actually, since there is no common interface, classes do not even have to call it clone() , they can call it copy() or something else.) You could use reflection to see if there is a public clone() method but it may be redundant.

0
source

Source: https://habr.com/ru/post/1413181/


All Articles