Instantiating Problem

  • Thread starter Thread starter Xarky
  • Start date Start date
X

Xarky

Hi,
I have the following problem:

public class NodeList
{
public NodeList next;
private int data;

public NodeList(int x)
{
this.next = null;
this.data = x;
}
} // end class


Now in the main program, I have a instance of NodeList, which has data
stored on it(generally a minimum of 10 nodes).

NodeList myNodeList; // by following a trace, all data entered is
correct

Now I require an exact copy of that data but in another object, that
does not point to that instance.

NodeList myNodeList;
NodeList other;

When I do,
other = myNodeList; // both have the same data and point to the same
instance.

My problem is that I am deleting nodes from object other, and those
nodes are also being deleted from object myNodeList.

Can someone help me solve my problem.


Thanks in Advance
 
Xarky,

That's because your your myNodeList and other variables are reference
variables. When you did the following:

myNodeList = new NodeList();

memory was allocated on the heap for this object and a reference to
it was placed in the variable myNodeList. Now, myNodeList basically
points that that object in that newly allocated memory. Then, when you
did this:

other = myNodeList;

the reference to that object in the previously allocated memory just
discussed is returned and assigned to the variable other.

What you could is instantiated other as this:

other = new NodeList();

and step throught the first NodeList and assign the values to your
other variable although that's not very ideal. You need to do a "deep
copy" which can be achieved by implementing the ICloneable interface.
Keep in mind, you must manually do the cloning/copying yourself within
the object. This looks like one of those first year, programming
language problems and if so I'm not sure if your class has discussed
implementing interfaces yet. Let us know if this helps set you on a
better path to solving your problem.

On 1 Nov 2004 01:50:10 -0800, (e-mail address removed) (Xarky) wrote:


* NodeList myNodeList;
* NodeList other;
*
* When I do,
* other = myNodeList; // both have the same data and point to the same
* instance.
*
* My problem is that I am deleting nodes from object other, and those
* nodes are also being deleted from object myNodeList.
*
* Can someone help me solve my problem.
*
*
* Thanks in Advance
 
Back
Top