简体   繁体   中英

How to access array list in different class

I want to access arraylist which I have created in BAL class in class named books

BAL class

public class BAL {
 ArrayList<members> member=new ArrayList<members>();
       members m1=new members(1,"Tom", "12345678", "No");
       members m2=new members(2,"Richard", "23456789", "No");
       members m3=new members(3,"Hillary", "45678901", "The Wind in the Willows");
       public void member_add()
       {
       member.add(m1);
       member.add(m2);
       member.add(m3);
       }
       public ArrayList<members> ls()
       {
           return member;
       }
}

books class

public class books {
public static void member_stch()
    {
       BAL bl=new BAL();

        System.out.println(bl.ls().size()); 
    }
}

And main method

public static void main(String[] args) {
        Scanner inp=new Scanner(System.in);
        BAL strt=new BAL();

        strt.member_add();
        books.member_stch(); // result 0
        System.out.println(strt.ls().size()); // result 3

}

I am getting 0 instead of 3 which is the size of Array List from books class

I m getting the expected result if I access array list in main

You are creating a second instance of BAL in your books class. It is a different object than the one created in main. You will need to pass either the BAL object from main into books, or its array list element, as a parameter to books.member_stch()

change like so in main:

books.member_stch();

to:

books.member_stch(strt);

and change member_stch from:

public static void member_stch()
{
   BAL bl=new BAL();

    System.out.println(bl.ls().size()); 
}

to:

public static void member_stch(BAL bl)
{
   System.out.println(bl.ls().size()); 
}

If you want to decouple BAL and books so that books does not need to know what a BAL is, you can replace

books.member_stch(strt);

with:

books.member_stch(strt.ls);

and:

public static void member_stch(BAL bl)
{
   System.out.println(bl.ls().size()); 
}

with:

public static void member_stch(ArrayList<Members> memberList)
{
   System.out.println(memberList.size()); 
}

The BAL instance you create in main invokes member_add() - and this adds those three instances you expect.

The BAL instance you create in member_stch() of the book class does not do this. It's not the same instance, and hence it's empty. It's unclear what the intention of the code is, but if you'd like those 3 member instances added to every BAL instance you create, consider invoking the add_member method in the constructor of BAL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM