How does this stack implementation work

Question from whoopdoop#7311

Im looking at this stack implementation and

public class ArrayStackOfStrings implements Iterable<String> {
    private String[] items;  // holds the items
    private int n;           // number of items in stack

    public ArrayStackOfStrings(int capacity) {
        items = new String[capacity];
    }

    public void push(String item) {
        items[n++] = item;
    }

    public String pop() {
        return items[--n];
    }

If I push an item using this push method, we are changing the items list, but how are we changing the variable n to update the new number of items? same with pop()

n++ does the mutation

wait so n is being changed impliciftly?

yes.

n++ means return the current value of n and also increment it.

--n means decrement it and then return the new value.

It's clearer to write it like this

public class ArrayStackOfStrings implements Iterable<String> {
    private String[] items;  // holds the items
    private int n;           // number of items in stack

    public ArrayStackOfStrings(int capacity) {
        items = new String[capacity];
    }

    public void push(String item) {
        items[n] = item;
        n++;
    }

    public String pop() {
        n--;
        return items[n];
    }

or

public class ArrayStackOfStrings implements Iterable<String> {
    private String[] items;  // holds the items
    private int n;           // number of items in stack

    public ArrayStackOfStrings(int capacity) {
        this.items = new String[capacity];
    }

    public void push(String item) {
        this.items[this.n] = item;
        this.n++;
    }

    public String pop() {
        this.n--;
        return this.items[this.n];
    }

so you see more clearly the order of things without remembering the difference between n++ and ++n

ohhh that makes so much sense

theres no diff between n-- and --n?

There is

int x = 5;
int y = x++;

// x is 6, y is 5
int x = 5;
int y = ++x;

// x is 6, y is 6

But just don't get clever with it, do it on its own line


<- Index