【问题标题】:ArrayList clearing itself in every iterationArrayList 在每次迭代中清除自身
【发布时间】:2017-10-29 03:56:58
【问题描述】:

我一直在通过抽象类练习继承,但是在使用构造函数和 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 的开关,而我的想法是它应该添加所有输入元素而无需重新设置,并且能够全部查阅

【问题讨论】:

  • 能否请您至少发布一些编译的代码?
  • 用 continue 代替 break 是否正常?在开关?使用 continue 创建一个 while(true) 循环,之后没有应用是正常的
  • 请格式化这个难以辨认的混乱。

标签: java inheritance arraylist


【解决方案1】:

您在每次循环迭代时创建一个新的接收对象。尝试将此定义放在循环之前,并在循环中使用此对象。此外,您需要为值编写一个空的构造函数和 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);
    }
}

【讨论】:

    【解决方案2】:

    该缺陷存在于Hotel 类的构造函数中。您在 Hotel 类的构造中定义 ArrayLists

    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 中将只存在一个项目

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-09
      • 2017-11-20
      • 2020-01-04
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多