Question

Hi please help me figure it out, what's wrong? Why when i do the 2nd pop from the stack it returns me the previous that already deleted?

public class R {

public static void main(String[] args) {
    Stack<int[][] > stack = new Stack<int[][] >();
    int[][] arr = new int[4][4];
    System.out.println("added");
    for(int i = 0; i < 4; i ++){
        for(int j = 0; j < 4;j++){
            arr[i][j] = i + j;
            System.out.print(i + j);
        }
        System.out.println();
    }
    stack.push(arr);
    System.out.println("added");
    for(int i = 0; i < 4; i ++){
        for(int j = 0; j < 4;j++){
            arr[i][j] = i * j;
            System.out.print(i * j);
        }
        System.out.println();
    }
    stack.push(arr);
    System.out.println(stack.size());

    arr = stack.pop();
    System.out.println("removed");
    for(int i = 0; i < 4; i ++){
        for(int j = 0; j < 4;j++){
            System.out.print(arr[i][j]);
        }
        System.out.println();
    }
    System.out.println(stack.size());
    int[][] arr2 = stack.pop();
    System.out.println("removed");
    for(int i = 0; i < 4; i ++){
        for(int j = 0; j < 4;j++){
            System.out.print(arr2[i][j]);
        }
        System.out.println();
    }
    System.out.println(stack.size());
    }
}

the first array is: 0123 1234 2345 3456

2nd: 0000 0123 0246 0369

than it should delete: 0000 0123 0246 0369

and than this: 0123 1234 2345 3456

Was it helpful?

Solution

You are rewriting the array, pushing the same instance twice. Create a new one each time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top