Java 仅添加最后一个元素的ArrayList
下面是for循环代码。我通过调用一个自定义显示函数发现aBook arrayList对象只添加了最后一个类对象三次。为什么会这样Java 仅添加最后一个元素的ArrayList,java,arraylist,Java,Arraylist,下面是for循环代码。我通过调用一个自定义显示函数发现aBook arrayList对象只添加了最后一个类对象三次。为什么会这样 Scanner s = new Scanner(System.in); ArrayList<LiFiAddressBook> aBook = new ArrayList<LiFiAddressBook>(); // taking input for every LifIAddressBook and adding them to
Scanner s = new Scanner(System.in);
ArrayList<LiFiAddressBook> aBook = new ArrayList<LiFiAddressBook>();
// taking input for every LifIAddressBook and adding them to the ArrayList.
for (int i = 0; i < 3; i++) {
System.out.println("Entry " + i+1);
System.out.print("Please Enter First Name: ");
String a = s.nextLine();
System.out.println();
System.out.print("Please Enter Last Name: ");
String b = s.nextLine();
System.out.println();
System.out.print("Please Enter Street Address: ");
String c = s.nextLine();
System.out.println();
System.out.print("Please Enter City: ");
String d = s.nextLine();
System.out.println();
System.out.print("Please Enter Zip Code: ");
int e = s.nextInt();
// in the next line we need to fire a blank scan function in order consume the nextLine. because after executing s.nextInt compiler skip a scan function for a weird reason
s.nextLine();
System.out.println();
LiFiAddressBook x = new LiFiAddressBook(a, b, c, d, e);
aBook.add(x);
}
}删除
static
关键字。本质上,该关键字确保这些变量只有一个实例。删除static
关键字。本质上,该关键字确保这些变量只有一个实例。Make:
static String first_name, last_name, street_address, city_state;
static int zip_code;
进入:
此外,您可能需要更改以下内容:
public static void display() {
致:
制作:
进入:
此外,您可能需要更改以下内容:
public static void display() {
致:
由于static关键字,每次构造函数
public-LiFiAddressBook(String,String,String,String,int)
被称为旧值被新值覆盖,当打印列表中的元素时,LiFiAddressBook类的对象变量指向相同的对象。因此打印类似的对象。
要明确的是,实际上LiFiAddressBook有3个实例。但是这些LiFiAddressBook实例的变量/属性引用了相同的对象 由于static关键字,每次构造函数
public-LiFiAddressBook(String,String,String,String,int)
被称为旧值被新值覆盖,当打印列表中的元素时,LiFiAddressBook类的对象变量指向相同的对象。因此打印类似的对象。
要明确的是,实际上LiFiAddressBook有3个实例。但是这些LiFiAddressBook实例的变量/属性引用了相同的对象 根据代码,这不可能发生。你能在显示列表元素的地方显示代码吗?你如何三次验证它是否是同一个对象?我怀疑问题出在
LiFiAddressBook
中。可能,每次您创建一个新的LiFiAddressBook
,它都会对以前实例化的对象的值进行踩踏(可能成员字段声明为static
或其他?)。@ajb是对的!猜得好;)从字段声明中删除静态限定符!根据代码,这不可能发生。你能在显示列表元素的地方显示代码吗?你如何三次验证它是否是同一个对象?我怀疑问题出在LiFiAddressBook
中。可能,每次您创建一个新的LiFiAddressBook
,它都会对以前实例化的对象的值进行踩踏(可能成员字段声明为static
或其他?)。@ajb是对的!猜得好;)从字段声明中删除静态限定符!
public static void display() {
public void display() {