注意:我按照我认为人们试图告诉我的方式编辑了代码,但它仍然没有给我想要的输出。现在我的输出是“examples.search.Person@55acc1c2”,但是我多次输入新的名字和姓氏。至少它可以通过代码而不会崩溃哈哈
我正在学习如何使用 ArrayList,并且需要加载包含我创建的对象实例的数组列表。我知道如何使用数组执行此操作,但对于此作业,我需要使用 ArrayList 执行此操作。这是我需要做的事情的示例。
// my "main" class
package examples.search;
import java.util.ArrayList;
import dmit104.Util;
public class MyPeople {
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<Person>();
Person tempPerson = new Person();
String firstName;
String lastName;
char choice = 'y';
int count = 1;
// fill my ArrayList
do {
people.add(tempPerson);
// I have a Util class that has a prompt method in it
firstName = Util.prompt("Enter First Name: ");
lastName = Util.prompt("Enter Last Name: ");
tempPerson.setFirstName(firstName);
tempPerson.setLastName(lastName);
count++;
choice = Util.prompt(
"Enter another person? [y or n]: ")
.toLowerCase().charAt(0);
} while (choice == 'y');
// display my list of people
for(int i = 0; i < people.size(); i += 1) {
System.out.print(people.get(i));
}
}
}
// my Person class which I am trying to build from
public class Person {
// instance variables
private String firstName;
private String lastName;
// default constructor
public Person() {
}
public String getFirstName(){
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
我尝试了多种方法,但无论如何我的 ArrayList 都没有填满。就像我提到的,我可以使用数组来做到这一点,即使我有一个加载的构造函数方法,但我没有。在我的实际作业中,我应该使用 set 方法来完成它。
我到处都找过了,但找不到问题的解决方案,而且周五我的教练不在。
提前非常感谢
狮子座
最佳答案
您必须创建一个Person
,然后将其添加
到ArrayList
中。
for (int i = 0; i < count; i++) {
Person person = new Person();
person.setFirstName("Foo");
person.setLastName("Bar");
people.add(person);
}
关于java - 如何使用我创建的对象实例加载 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18027567/