Algorithms, 4th Edition: do not understand an example about aliasing/reference

90 Views Asked by At
Counter c1 = new Counter("ones"); 
c1.increment(); 
Counter c2 = c1; 
c2.increment(); 
StdOut.println(c1);

class code link: https://introcs.cs.princeton.edu/java/33design/Counter.java

public class Counter implements Comparable<Counter> {

    private final String name;     // counter name
    private final int maxCount;    // maximum value
    private int count;             // current value

    // create a new counter with the given parameters
    public Counter(String id, int max) {
        name = id;
        maxCount = max;
        count = 0;
    } 

    // increment the counter by 1
    public void increment() {
         if (count < maxCount) count++;
    } 

    // return the current count
    public int value() {
        return count;
    } 

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

    // compare two Counter objects based on their count
    public int compareTo(Counter that) {
        if      (this.count < that.count) return -1;
        else if (this.count > that.count) return +1;
        else                              return  0;
    }


    // test client
    public static void main(String[] args) { 
        int n = Integer.parseInt(args[0]);
        int trials = Integer.parseInt(args[1]);

        // create n counters
        Counter[] hits = new Counter[n];
        for (int i = 0; i < n; i++) {
            hits[i] = new Counter(i + "", trials);
        }

        // increment trials counters at random
        for (int t = 0; t < trials; t++) {
            int index = StdRandom.uniform(n);
            hits[index].increment();
        }

        // print results
        for (int i = 0; i < n; i++) {
            StdOut.println(hits[i]);
        }
    } 
}

enter image description here

The book says it will print "2ones", and the process is shown in the picture above. But I can't get it. In my opinion, c1 adds so its object adds, so we get "2";then copy c1 to c2, c2 gets "2" as well. As c2 adds, the object will turn to the unknown next grid. When printing c1, I think we should get "2" rather than "2ones". So what's wrong with my process? Thanks in advance.

1

There are 1 best solutions below

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

I think this demonstration should just show Referencing. Since you are creating just 1 object of type counter. And assigning the value of c1, to the variable (Counter) c2 and then use the method .increment() on the variable c2 , c1 will change . Since c2 and c1 are both referencing to the same object in memory . So changes to c1 and c2 will both affect the same object.