Categories > Coding > Javascript >
Questions about Copy constructor Java
Posted
I have a question about Java copy building. Consider the following group:
I can say new(Integer(other.id)) in the copy constructor to receive a new integer object being supplied to the constructor, but I can't say new T(other.data) since the compiler will complain I can't instantiate the type T. How can I ensure that when the generic item is copied, it does not just pass a reference, causing the two objects to share the underlying data?
Also, the getLinks function does a new and creates a new object of the list, but is that going to deep copy and build a new object of the things included in the list or will it only have references to the current objects list items, resulting in two lists both pointing to the same data? See the comments / code below. Thank you in advance for your assistance.
class DigraphNode<T>
{
Integer id;
T data;
ArrayList<DigraphNode<T> > links;
public DigraphNode(Integer i)
{
id = i;
links = new ArrayList<DigraphNode<T> >();
}
public DigraphNode(Integer i, T d)
{
id = i; data = d;
links = new ArrayList<DigraphNode<T> >();
}
public DigraphNode(DigraphNode<T> other)
{
other.id = new Integer(other.id);
other.data = other.data; // line in question
this.links=other.getLinks(); // also will create a new list with references
// or will it deep copy the items contained in the list?
// see getLinks() method below
}
public void setData (T d ) { data = d; }
public void addLink (DigraphNode<T> n) { links.add(n); }
public void addLinks (ArrayList<DigraphNode<T> > ns) { links.addAll(ns); }
public ArrayList<DigraphNode<T> > getLinks()
{
return new ArrayList<DigraphNode<T> >(links);
}
public void printNode()
{
System.out.print("Id: " + id + " links: ");
for ( DigraphNode<T> i : links )
{
System.out.print(i.id + " ");
}
System.out.println();
}
}
Added
thank you for help it worked.
Cancel
Post
Users viewing this thread:
( Members: 0, Guests: 1, Total: 1 )
Cancel
Post