注意:我編輯我的代碼,我認爲人們試圖告訴我,但它仍然不會給我所需的輸出。現在我的輸出是「[email protected]」,但很多時候我輸入新的姓氏和名字。至少它是通過代碼崩潰大聲笑如何加載我創建的對象的實例的ArrayList
我正在學習如何使用ArrayLists,並需要加載一個數組列表與我創建的對象的實例。我知道如何使用數組來完成此任務,但是對於此任務,我需要使用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()。另外,除非你非常需要一個可變類,否則你應該總是嘗試將你的值對象實例化爲不可變類型的實例。在你的情況下,lastname和firstname應該聲明爲final,並在Person()構造函數中設置爲它們的初始值。 – scottb
你說你知道如何爲數組做這件事,它並沒有那麼不同,在創建'ArrayList''人後,你沒有任何對象,你必須創建它們並將它們添加到列表中。 – madth3
哦,雅斯科特,它在我的課上說,聯繫它應該說人。當我將代碼粘貼到lol中時,我忘了改變這一點。我實際上正在做一個聯繫人管理器,我需要這樣做,因此用戶可以添加和刪除聯繫人並能夠更改它們(以防有人更改電子郵件,電話號碼等) – leoJaxx