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 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);


    }

这是我的 LiFiAddressBook 类

public class LiFiAddressBook {

static  String  first_name, last_name, street_address, city_state;
static int zip_code;

public LiFiAddressBook(String first, String last, String street, String city, int zip) {
  //constructor for class object.
    first_name = first;
    last_name = last;
    street_address = street;
    city_state = city;
    zip_code = zip;
}

public  String get_first() {
    return first_name;
}

public String get_last() {
    return last_name;
}

public String get_address() {
    return street_address;
}

public String get_city() {
    return city_state;
}

public String get_zip() {
    return Integer.toString(zip_code);
}

public static void display() {
    System.out.println("First Name: "+first_name);
    System.out.println("Last Name: "+last_name);
    System.out.println("Street Address"+street_address);
    System.out.println("City State: "+city_state);
    System.out.println("Zip Code: "+zip_code);


}

}

最佳答案

由于static关键字,每次构造函数
public LiFiAddressBook(String, String, String, String, int)
被称为旧值被新值覆盖,并且当打印列表中的元素时,LiFiAddressBook类的对象的变量指向相同的对象。因此打印类似的对象。

需要明确的是,实际上有 3 个 LiFiAddressBook 实例。但这些 LiFiAddressBook 实例的变量/属性引用相同的对象。

关于java - ArrayList仅添加最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32491260/

相关文章:

java - 在水平布局中显示 ListView 时出现问题?

JAVA获取arraylist的每个值

java - 我应该返回 List 还是 ArrayList?

java - Tomcat 7管理器无法登录

java - TCP 套接字连接 Java Client<-> c++ 服务器中的意外行为

java - 图像在 3D 空间中绕 Y 轴旋转

java - 源代码中的密码 - 安全吗?

java - 优先级队列/ArrayList 的 IndexOutOfBoundsException

javascript - 我如何比较两个在javascript中长度不同的数组?

Java用字母数字字符串排序对象arraylist