سؤال

my program is simple. I have a class with 2 methods. I have another class where those two methods are called. When the first method is called, the arraylist is initialized and filled with some Objects, then the second method is called simply to tell the size of the arraylist and print it out. I cant understand why I always get an empty when second method is called. However when I print the array inside the first method I get the size and all it elements. Arraylist is public.. please have a look at the code..

in class 1

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

in class 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);



}

So, the results are that when calling the first method i can see the items and size number adding or deleting products (have experimented a lot) when calling the other method I always get 0 for size and empty array. I have tried this with a public string and methods alter the string when they are called. So I guess its something with the ArrayList.. THANK YOU!

هل كانت مفيدة؟

المحلول

You are creating a new instance of Items and then calling viewItems() method.you have to invoke viewItems() on the same instance on which you invoked init()

Items initialize = new Items();
initialize.init(); 
initialize .viewItems();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top