Reputation: 593
I'm trying to create a generic container which has a copy-constructor. I'm having trouble using the clone method even though I have coded it in. Here's what I have so far:
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 get my copy-constructor to work?
Upvotes: 3
Views: 1638
Reputation: 122439
Unfortunately in Java, there is no generic way to clone an object. Some classes have a public clone()
method, which allows you to clone, but there is no common superclass or interface with a public clone()
method. (In fact, because there is no common interface; classes don't even have to call it clone()
; they could name it copy()
or something else.) You could use reflection to see if there is a public clone()
method, but that might be overkill.
Upvotes: 0
Reputation: 470
Usually you don't need to clone the 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 is now referenced by both two collection A and B.
Upvotes: 3
Reputation: 4693
public MyBox(MyBox<T> other)
{
this.list = new ArrayList<T>(other.getList());
}
but you must add a getter for your list first in this case.
UPD. this makes shallow copy.
Upvotes: 0
Reputation:
How about restricting the generic to Clonable, then it's certain that the cloning of the items will be allowed:
public class MyBox<T extends Clonable> {
...
Upvotes: 0