I am trying to add many objects to a LinkedList
. The first (incorrect way) that I tried was the following:
Person class:
public class Person
{
public double age;
public String name;
}
(first way) Main file:
import java.util.LinkedList;
public class Main
{
public static void main(String[] args)
{
LinkedList<Person> myStudents = new LinkedList<Person>();
Person currPerson = new Person();
for(int ix = 0; ix < 10; ix++)
{
currPerson.age = ix + 20;
currPerson.name = "Bob_" + ix;
myStudents.add(currPerson);
}
String tempName_1 = myStudents.get(1).name; \\This won't be "Bob_1"
String tempName_2 = myStudents.get(2).name; \\This won't be "Bob_2"
}
}
The second way:
import java.util.LinkedList;
public class Main
{
public static void main(String[] args)
{
LinkedList<Person> myStudents = new LinkedList<Person>();
for(int ix = 0; ix < 10; ix++)
{
Person currPerson = new Person();
currPerson.age = ix + 20;
currPerson.name = "Bob_" + ix;
myStudents.add(currPerson);
}
String tempName_1 = myStudents.get(1).name; \\This will be "Bob_1"
String tempName_2 = myStudents.get(2).name; \\This will be "Bob_2"
}
}
The second way works just fine, but is there a better (or more correct) way to do it? If the second way only uses the addresses of those objects, will that make it risky (as this address might be replaced at later point)?