Discuss / Java / 请修复Score的构造方法,使得外部代码对数组的修改不影响Score实例的int[]字段。

请修复Score的构造方法,使得外部代码对数组的修改不影响Score实例的int[]字段。

Topic source
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] scores = new int[] { 88, 77, 51, 66 };
        Score s = new Score(scores);
        s.printScores();
        scores[2] = 99;
        s.printScores();
    }
}

class Score {
    private int[] scores;
    public Score(int[] scores) {
        this.scores = Arrays.copyOf(scores, scores.length);
    }

    public void printScores() {
        System.out.println(Arrays.toString(scores));
    }
}

  • 1

Reply