我正在尝试将许多对象添加到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"
}
}
第二种方法效果很好,但是有更好(或更正确)的方法吗?如果第二种方式仅使用这些对象的地址,这是否会带来风险(因为该地址稍后可能会被替换)?
最佳答案
第二种方法是正确的,尽管有人可能会说你可以这样做:
import java.util.LinkedList;
public class Main
{
public static void main(String[] args)
{
LinkedList<Person> myStudents = new LinkedList<Person>();
Person currPerson = null;
for(int ix = 0; ix < 10; ix++)
{
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"
}
}
并在循环外声明 currPerson。这应该会“节省”一点空间,但这是一个无限小的优化。无论如何,JVM 可能会为您优化这一点。
无论如何 - 正如您所看到的,第二种方法是可行的方法。
关于java - 按值将对象添加到 LinkedList 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10273461/