gpt4 book ai didi

调用方法时,java ArrayList 始终为空

转载 作者:行者123 更新时间:2023-11-29 05:48:50 24 4
gpt4 key购买 nike

我的程序很简单。我有一个有 2 种方法的类。我有另一个类,其中调用了这两个方法。当调用第一个方法时,arraylist 被初始化并填充一些对象,然后调用第二个方法只是告诉 arraylist 的大小并将其打印出来。我不明白为什么在调用第二种方法时我总是得到一个空的。但是,当我在第一种方法中打印数组时,我得到了大小及其所有元素。 Arraylist 是公开的。请查看代码。

在第 1 类

Items initialize = new Items();
initialize.init();
Items view = new Items();
view.viewItems();

在第 2 类

public class Items {

public String id;
public String name;
public String details;
public String stock;

public ArrayList<Items> myList = new ArrayList<Items>();

public void init(){

Items item1 = new Items();


item1.id = "0023";
item1.name = "Round Table";
item1.details = "Brown, high quality wood blah blah..";
item1.stock = "34";
myList.add(item1);


if(myList.size()==0){
System.out.println("There are no products to display");
}

Iterator<Items> iterator = myList.iterator();
System.out.println(myList.size());
System.out.println("Products Available:");
while(iterator.hasNext()){
Items current = iterator.next();

System.out.println("\nID: " +current.id + "\nTitle: "+current.name+"\nDescreption: "+current.details+"\nAmount: "+current.stock);

}

public void viewItems() {

int size = myList.size();

if(myList.size()==0){
System.out.println("There are no products to display");
}

Iterator<Items> iterator = myList.iterator();
System.out.println(myList.size());
System.out.println("Products Available:");
while(iterator.hasNext()){
Items current = iterator.next();

System.out.println("\nID: " +current.id + "\nTitle: "+current.name+"\nDescreption: "+current.details+"\nAmount: "+current.stock);



}

因此,结果是,当调用第一种方法时,我可以看到添加或删除产品的项目和尺寸编号(已经试验了很多),而当调用另一种方法时,我总是得到 0 的尺寸和空数组。我已经用公共(public)字符串试过了,方法在调用时改变了字符串。所以我猜它与 ArrayList 有关系。谢谢!

最佳答案

您正在创建一个 Items 的新实例,然后调用 viewItems() 方法。您必须在调用 的同一实例上调用 viewItems() >初始化()

Items initialize = new Items();
initialize.init();
initialize .viewItems();

关于调用方法时,java ArrayList 始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14801306/

24 4 0