Hello.

The question is how to reach the array?

When I call from class A, I get the length of the array 0, although it is filled with more than 100 elements. If you pull the content from class C until it fills it, it will show all the content,

Class A { B b = new B(); C c = new C(); public static void main(){ b.doSmth(); System.out.print(c.getArrayList()); } } Class B { C c=new C(); c.setArrayList(String s); } Class C { private ArrayList list=new ArrayList(); setArrayList(String s){ list.add(s); } getArrayList(){ return list.size(); } } 

    1 answer 1

    You have two different objects of class C , so the array is empty.

    Your code should look like this:

     public class A { B b; A(B b) { this.b = b; } public void method() { b.method(); } public static void main(String[] args) throws Throwable { C c = new C(); B b = new B(c); A a = new A(b); a.method(); System.out.println(abcgetArrayList()); } } class B { C c; public B(C c) { this.c = c; } void method() { c.setArrayList("hello"); } } class C { private ArrayList list = new ArrayList(); public void setArrayList(String s) { list.add(s); } public int getArrayList() { return list.size(); } } 

    Generally not a very good composition of classes, you need to think about it better.

    • I apologize for the inaccuracy in the question. I refused a static, this is the easiest option, but I want to refuse it - Dred
    • This code will also work without statics, but the creation of objects will have to be specified in main. because non-static fields from the static method are not known as available. - Artem Konovalov
    • So, and here begins the difficulty. Since this example is, of course, a simplified version. Actually, I have class A, calls class B, which calls C, in which an array is formed, receiving data from class C, and then, the next item in my class A is called class D, where the information from the array is from class C Ie something like A-> B-> C; A-> D-> getArray (C). That is, using your example, I need to insert something like class A { - Dred in the method
    • class A {public static void main () {B b = new B (); C c = new C (); D d = new D (); d.doSmth (b.doSmth.c.getArray ()); System.out.print (c.getArrayList ()); }} Something like that ... or I can't even imagine - Dred
    • @Dred changed the answer - Artem Konovalov