Storing Object values versus object address in a linkedlist
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Wayne_Crichlow
Posted On:   Tuesday, November 12, 2002 12:32 PM

I have an implementation of a linked list which I would like to populate with copies of the values of a custom object. The problem I am having is that the address of the custom object is being placed on the list and not the values. As a result I get a list which contains all the same values(i.e. the address of the custom object). I am sure this problem is related to my lack of understanding of how to pass an objects value versus it's referance in Java. I would greatly appreciate it if someone could help point out an effective way of doing this. The relavant code is listed below: The desired outcome would be to have copies of the value retrieved from the result set placed on the linkedlist. public class RStoArray    More>>

I have an implementation of a linked list which I would like to populate with copies of the values of a custom object. The problem I am having is that the address of the custom object is being placed on the list and not the values. As a result I get a list which contains all the same values(i.e. the address of the custom object). I am sure this problem is related to my lack of understanding of how to pass an objects value versus it's referance in Java. I would greatly appreciate it if someone could help point out an effective way of doing this. The relavant code is listed below:

The desired outcome would be to have copies of the value retrieved from the result set placed on the linkedlist.



			
public class RStoArray
{

public static MyObject copyData(MyObject wk1,ResultSet rs)
{
try
{
wk1.id = rs.getInt(1);
}
catch ( SQLException e )
{
System.out.println ("Error in copyData....");
e.printStackTrace();
}
return wk1;
}

public static void main(String[] args)
{
Statement stmt = null;
try
{
connect();
ResultSet result = stmt…….

Sc1 t1 = new MyObject();
List list1 = new LinkedList();

while(result.next());
{
copyData(t1,result);
list1.add(t1);
}

at this point I end up with a linked list with every node containing the address of the last value placed on the list.

Thanks in advance for any help.


}
catch(SQLException e)
{
System.err.println(e.getMessage());
}
}
}
   <<Less

Re: Storing Object values versus object address in a linkedlist

Posted By:   Brian_Kapellusch  
Posted On:   Tuesday, November 12, 2002 01:07 PM

Wayne,



You're only creating a total of 1 instance of MyObject, so that's why you're experiencing the problem that you are. You also have a semicolon after your while loop, so it's probably executing only once (unless that was a typo).

try:




Sc1 t1 = null;
List list1 = new LinkedList();

while(result.next()) {
t1 = new MyObject();
copyData(t1,result);
list1.add(t1);
}
About | Sitemap | Contact