我正在尝试将许多对象添加到LinkedList
. 我尝试的第一个(不正确的方法)如下:
人物类:
public class Person
{
public double age;
public String name;
}
(第一种方式)主文件:
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"
}
}
第二种方式:
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"
}
}
第二种方法效果很好,但是有更好(或更正确)的方法吗?如果第二种方式只使用这些对象的地址,那会不会有风险(因为这个地址可能会在以后被替换)?