Алгоритмы, 4-е издание: не понимаю пример с алиасами / ссылками - PullRequest
0 голосов
/ 20 ноября 2018
Counter c1 = new Counter("ones"); 
c1.increment(); 
Counter c2 = c1; 
c2.increment(); 
StdOut.println(c1);

ссылка на код класса: 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

В книге говорится, что она напечатает «2one», и процесспоказано на рисунке выше.Но я не могу получить это.По моему мнению, c1 добавляет так, что его объект добавляет, поэтому мы получаем «2», затем копируем c1 в c2, c2 также получает «2».Как добавляет c2, объект превратится в неизвестную следующую сетку.При печати c1, я думаю, мы должны получить «2», а не «2ones».Так что не так с моим процессом?Заранее спасибо.

1 Ответ

0 голосов
/ 20 ноября 2018
Counter c1 = new Counter("ones"); 
c1.increment(); 
Counter c2 = c1; 
c2.increment(); 
StdOut.println(c1);

Я думаю, что эта демонстрация должна просто показать ссылки.Так как вы создаете только 1 объект типа counter.И присвоение значения c1 переменной (Counter) c2, а затем использование метода .increment () для переменной c2, c1 изменится.Поскольку c2 и c1 оба ссылаются на один и тот же объект в памяти.Таким образом, изменения в c1 и c2 затронут один и тот же объект.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...