[英]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类中创建的arraylist ,该类名为books
BAL class BAL类
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 我从书籍类得到0而不是3,这是数组列表的大小
I m getting the expected result if I access array list in main 如果我访问main中的数组列表,我会得到预期的结果
You are creating a second instance of BAL in your books class. 您正在图书类中创建第二个BAL实例。 It is a different object than the one created in main.
它是与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()
您将需要将BAL对象从main传递到book中,或者将其array list元素传递给books.member_stch()
change like so in main: 主要更改如下:
books.member_stch();
to: 至:
books.member_stch(strt);
and change member_stch from: 并将member_stch从:
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 如果要使BAL和书籍脱钩,使书籍不需要知道BAL是什么,则可以替换
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. 您在main中创建的
BAL
实例将调用member_add()
-这将添加您期望的这三个实例。
The BAL
instance you create in member_stch()
of the book class does not do this. 您在book类的
member_stch()
中创建的BAL
实例不执行此操作。 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. 尚不清楚代码的意图是什么,但是如果您希望将这3个成员实例添加到您创建的每个
BAL
实例中,请考虑在BAL的构造函数中调用add_member
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.