The P42 example of the fourth edition of the algorithm does not understand

algorithm (4th edition) Xie Luyun translated P42 example

public class Counter{
    Counter(String id);
    void increment();
    int tally();
    String toString();
}
// return a string representation of this counter
public String toString() {
    return name + ": " + count;
} 

Note: thank you @ LEON for the Counter class implementation link: https://introcs.cs.princeton.

Counter c1 = new Counter("ones"); 
c1.increment(); 
Counter c2 = c1; 
c2.increment(); 
StdOut.println(c1);

clipboard.png

The

book says that the final output will print out "2ones" with such a picture.
but I don"t understand. What I currently understand is that C1 is a reference to the object of new, and this object is also a reference to "ones" because the object is initialized to "ones". When
C1 increases, the object adds a grid to "2", and the c1 reference is copied to c2, so c2 also points to "2". If c2 is added, it points to an unknown grid under "2". At this point, C1 is output, corresponding to the same "2".
I understand that the result should output "2", but the book says that the printed result is "2ones". I don"t know where I misunderstood it. Look forward to the help of kind-hearted people.

Dec.01,2021

// return a string representation of this counter
    public String toString() {
        return name + ": " + count;
    } 

this is implementation in newest edition of Algorithms, posted on the official site

https://introcs.cs.princeton.
Menu