我有一个静态的产品类型列表。当我从 Shopowner 类填充此列表时,它工作正常,但是当我编译 Customer.java 时,该列表返回空白集。为什么填充的列表不保留?
class Products {
String name;
int itemcode;
Products(){}
static List <Products> list = new ArrayList<Products>();
Products(String name,int itemcode)
{
this.name=name;
this.itemcode=itemcode;
}
public String toString()
{return (name+""+itemcode);}
}
class Shopowner {
public static void main (String ...at)
{
Products o = new Products("Shamppo",12);
Products.list.add(o);
Products o1 = new Products("choco",1112);
Products.list.add(o1);
System.out.println(Products.list); //prints fine
}
}
class Customer {
public static void main (String args[])
{
System.out.println(Products.list); //prints []
}
}
OutPut(编译Customer.jav时)
[]
最佳答案
请参阅下面的部分代码:
public static void main (String ...a)
{
Products o= new Products("Chocolate");
o.addToList();
Products o1= new Products("Icecream");
o1.addToList();
new Products().showList(); //This line is the culprit
您正在对象 o 和 o1 中添加列表,并且您正在完全不同的对象上调用 showList() new Products().showList();?
注意: 它适用于静态列表,因为它在 Product 类的所有对象之间共享,而非静态列表则不然。
关于java - 列表的范围和生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18165470/