0

So I have a class without a constructor and I was wondering how the values are initialized by the default construct. Will elementWithCachedMax be initialized to new LinkedList? How and Why? Where can I learn more about how the default constructor initializes member variables?

public static class Stack {
    // Stores (element, cached maximum) pair.
    private Deque<ElementWithCachedMax> elementWithCachedMax
            = new LinkedList<>();

    public boolean empty() { return elementWithCachedMax.isEmpty(); }

    public Integer max() {
        if (empty()) {
            throw new IllegalStateException("max(): empty stack");
        }
        return elementWithCachedMax.peek().max;
    }

    public  Integer pop() {
        if (empty()) {
            throw new IllegalStateException("pop(): empty stack");
        }
        return elementWithCachedMax.removeFirst().element;
    }
    public static void print(){
        System.out.println("HI");
    }

    public void push(Integer x) {
        elementWithCachedMax.addFirst(
                new ElementWithCachedMax(x, Math.max(x, empty() ? x : max())));
    }
}
Matt
  • 501
  • 4
  • 14
  • 1
    Your assumption that the default constructor is initializing your variable is incorrect. – azurefrog Sep 20 '17 at 19:52
  • could you give me an explanation? – Matt Sep 20 '17 at 19:54
  • Possible duplicate of [Java default constructor](https://stackoverflow.com/questions/4488716/java-default-constructor) – azurefrog Sep 20 '17 at 19:55
  • 2
    Variable initialization happens during object creation, but often isn't done in a constructor. For instance, in your code you are initializing `elementWithCachedMax` as part of its declaration. – azurefrog Sep 20 '17 at 19:57

0 Answers0