There is one stupid question. Why the output of the following program is 0. Code:

import java.util.ArrayList; public class Testing { public static void main(String[] argv) { Stack stack = new Stack(); Mov mov = new Mov(); System.out.println(stack.getSize()); } } class Mov { private int c = 0; public Mov() { Stack stack = new Stack(); for(int i=0;i<15;i++) { c++; stack.push(c); } } } class Stack { private ArrayList<Integer> list = new ArrayList<Integer>(); public void push(int c) { list.add(c); } public int getSize() { return list.size(); } } 

    3 answers 3

     import java.util.ArrayList; public class Testing { public static void main(String[] argv) { Mov mov = new Mov(); Stack stack = move.getStack(); System.out.println(stack.getSize()); } } class Mov { private int c = 0; public Mov() { } public Stack getStack() { Stack stack = new Stack(); for(int i=0;i<15;i++) { c++; stack.push(c); } return stack; } } class Stack { private ArrayList<Integer> list = new ArrayList<Integer>(); public void push(int c) { list.add(c); } public int getSize() { return list.size(); } } 

    somehow something like that)

    • Thank. I understood. - burningsky

    In the constructor of the Mov () class, you perform actions with a temporary non-stack object that is created in the main () method.

    • I would not call the stack inside the muve a temporary object, but the fact that the object is a stack inside the muve and in Maine is different objects - fact =) - Gorets
    • Is it not destroyed when exiting the constructor? - Po_Olaris
    • How, in this case, can one get the necessary output in main (in this case, 15) and can it be done in principle using this simple approach? anywhere program). - burningsky
    • In the main way - in any way (at least, this seems to me to be something very difficult in this context). And why not an option to move the line "System.out.println (stack.getSize ())" to the end of the Mov () constructor? - Po_Olaris
    • In this case, it may be an option, but I'm interested in the very principle of transferring values ​​from one class to another using a class like Stack. - burningsky

    It's very simple, you call the method getsise () on the stack Object,
    in which no Mov object was created, therefore, the question
    How will the data appear on the stack if you don’t put them there ??)) Therefore, the result is that the stack size is 0 =)