0

I create a stack class with the name StackOfBook. I need 2 stacks so I create this on my main class:

StackOfBook stack1 = new StackOfBook();

while (true) {
    long number = sc.nextLong();
    if (number == -1) {
        break;
    }
    stack1.push(number);
}

StackOfBook stack2 = new StackOfBook(stack1.getTop());

This is my stack class:

private int top = 0;
private ArrayList<Long> arrBook;

public StackOfBook(){
    arrBook = new ArrayList<Long>();
}

public StackOfBook(int size){
    arrBook= new arrBook<Long>(size);
}

public int getTop() {
    return this.top;
}

I tried to initialize the ArrayList in the second stack without changing its top, but when I tried this the ArrayList in my stack2 doesn't initialize with stack1.getTop(). I have checked the variable size in the constructor and it has a value. Why is it wrong?

Daniel Beck
  • 16,972
  • 5
  • 29
  • 49
Irvan
  • 123
  • 1
  • 9

2 Answers2

2

ArrayList is backed by, as its name indicates, an array. Arrays are fixed-size; when the ArrayList gets near the array's capacity, it resizes it - it creates a new array, copies everything over, and ditches the old array.

When you initialize an ArrayList with a "size", that's actually its initial default capacity. It does not initialize anything into the array. The ArrayList is still empty after you create it; you still need to actually add values to the ArrayList.

dcsohl
  • 6,450
  • 1
  • 23
  • 40
0

The int argument to the ArrayList(n) constructor is merely used to set an initial capacity for the list. Its size is still zero until you put something in it. The initial capacity is used internally so that the list does not have to reallocate more space until you put more than n items in it.

FredK
  • 4,036
  • 1
  • 6
  • 11