简体   繁体   English

我如何最好地用原始对象填充此数组?

[英]How would I best go about populating this array with original objects?

I have an array: 我有一个数组:

ArrayList<Person> people = new ArrayList();

And I want to add people to the array, but I don't think it will work because all the objects will have the same name. 我想将人员添加到数组中,但是我认为它不会起作用,因为所有对象都具有相同的名称。

Person person = new Person();
person.firstName = firstNameTextField.getText();
person.lastName = lastNameTextField.getText();
//Etc
people.add(person);

My question is, can I populate array with objects of the same variable name? 我的问题是,我可以用相同变量名称的对象填充数组吗? If not, how can I still use People objects? 如果没有,如何仍然使用People对象?

Objects are unrelated to their variable names! 对象与它们的变量名无关! Yes, ofcourse it will work! 是的,当然可以!

Yes, you won't have any issue with what you're describing. 是的,您所描述的内容不会有任何问题。

You'll end up with something like this: 您将得到如下所示的结果:

Person person = new Person();
person.firstName = firstNameTextField.getText();
person.lastName = lastNameTextField.getText();
people.add(person);

person = new Person(); // <-- reinitializing person.
person.firstName = firstNameTextField.getText();
person.lastName = lastNameTextField.getText();
people.add(person);

At this point List contains two unique Person objects. 此时,List包含两个唯一的Person对象。 Iterating over them might look something like this: 遍历它们可能看起来像这样:

ArrayList<Person> people = new ArrayList();
// add a bunch of Person objects like we did above

for(int i = 0; i < people.size(); i++) {
    System.out.println("Found person: " + people.get(i).firstName);
}

The fact that you continue to make the people.add(person) call, doesn't necessarily you're repeatedly adding the same person to your list over and over again. 您继续进行people.add(person)调用的事实,并不一定要一遍又一遍地将同一个人添加到列表中。 In the case shown above, unique Person objects are being added and can be accessed independently as shown in the for loop. 在上述情况下,将添加唯一的Person对象,并且可以像for循环中所示独立地对其进行访问。

If you are Lazy you can also use a Constructor in People. 如果您很懒,也可以在People中使用构造函数。

class Person {
 public Person(String firstname, String lastname) { 
 this.firstname=firstname;      
 this.lastname=lastname; 
}
}

and then ... 接着 ...

people.add(new People("tom", "lastnameoftom"));
people.add(new People("Susi", "SusisLastname"));

and so on.. 等等..

But to answer your Question.. Everytime you use a new on a var, it will be reinitialized. 但要回答您的问题。每次您在var上使用new时,它将被重新初始化。 the Compiler will translate this: 编译器将翻译为:

People people = new People();
people.setSetter(data);

people = new People();
people.setSetter(otherdata);

to (example) 到(示例)

People a = new People();
a.setSetter(data);

People b = new People();
b.setSetter(otherdata);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM