私のプログラムは簡単です。私は2つのメソッドを持つクラスを持っています。これらの 2 つのメソッドが呼び出される別のクラスがあります。最初のメソッドが呼び出されると、arraylist が初期化され、いくつかのオブジェクトが格納されます。次に、2 つ目のメソッドが呼び出されて、単に arraylist のサイズが通知され、出力されます。2番目のメソッドが呼び出されたときに常に空になる理由がわかりません。ただし、最初のメソッド内で配列を出力すると、サイズとそのすべての要素が取得されます。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 を取得します。私はパブリック文字列でこれを試しましたが、メソッドは呼び出されたときに文字列を変更します。だから私はArrayListで何かを推測..ありがとう!