ArrayList在每次迭代中清除自身

时间:2017-05-28 21:51:49

标签: java inheritance arraylist

我一直在练习继承和抽象类,但是我在使用构造函数和ArrayList时遇到了一些麻烦。

每次我查阅添加到我的Arraylist的所有信息时,他们似乎只打印最后添加的元素这是我到目前为止所得到的...

public static void main(String[] args) throws IOException  {
do{
switch(menu){
case 1:
int x=//random generated number;
String name=//insert name;
reception add=new Reception(x,name);continue;


Public class reception extends Hotel{
public Reception(int number,String name,){
super(number,name);
}

import java.util.ArrayList;

public abstract class Hotel {
    ArrayList<Integer> numerodehotel = new ArrayList<Integer>();
    ArrayList<String> residente1 = new ArrayList<String>();


    public Hotel(int number, String resident){
    this.resident1.add(resident);
    this.hotelroomnumber.add(number);
    }

每当我尝试打印所有元素时,它们似乎只显示两个ArrayList中最后添加的元素,几乎就像在每次迭代中重置一样。

在主类中有一个带有do的开关,而我的想法是它应该添加所有输入元素而不重新发布并且能够全部查阅

2 个答案:

答案 0 :(得分:0)

您在每次循环迭代时创建一个新的接收对象。尝试在循环之前放置此定义并在循环中使用此对象。此外,您需要为值编写空构造函数和getter / setter:

reception add=new Reception();
do {
    ...
    add.setNumerodehotel(x);
    add.setResidente1(name);
} while (...)

public abstract class Hotel {
    ArrayList<Integer> numerodehotel = new ArrayList<Integer>();
    ArrayList<String> residente1 = new ArrayList<String>();

    public Hotel(){
    }

    public void setNumerodehotel(int number){
       this.hotelroomnumber.add(number);
    }

    public void setResidente1(String resident){
       this.resident1.add(resident);
    }
}

答案 1 :(得分:0)

该缺陷位于Hotel类的构造函数中。您正在构建ArrayLists

时定义Hotel
public abstract class Hotel {
    // Every time you create a new Hotel these two lines are executed
    ArrayList<Integer> numerodehotel = new ArrayList<Integer>();
    ArrayList<String> residente1 = new ArrayList<String>();

    public Hotel(int number, String resident){
        this.resident1.add(resident);
        this.hotelroomnumber.add(number);
    }
}

这类似于这样做

public abstract class Hotel {
    ArrayList<Integer> numerodehotel;
    ArrayList<String> residente1;

    public Hotel(int number, String resident){
        numerodehotel = new ArrayList<Integer>();
        residente1 = new ArrayList<String>();
        this.resident1.add(resident);
        this.hotelroomnumber.add(number);

    }
}

正如您所看到的,每次创建Reception(新的Hotel)时,都会创建一个新的ArrayList,然后在ArrayLists <中只存在一个项目/ p>

您可能只想从构造函数中删除添加并通过单独的方法添加。

相关问题