public class Theft{
  private String[] time =new String[4];
  public String[] getTime() {
    return time = Arrays.copyOf(time, 4);
  }

  public void setTime(String[] time) {
    this.time = time;
  }
}


运行时

Theft theft =new Theft();
theft.getTime()[0]="sss";
theft.getTime()[0]="aaa"+theft.getTime()[0];
System.out.println(theft.getTime()[0]);


为什么打印“ sss”而不是“ aaasss”?该值似乎未更改。

最佳答案

因为您每次都在创建它的副本。

public class Theft {
    private String[] time = new String[4];

    public String[] getTime() {
        return time; // Return the time itself, not a copy
    }

    public void setTime(String[] time) {
        this.time = time;
    }
}


输出:aaasss

关于java - 为什么theft.getTime()[0] =“aaa” + theft.getTimie()[0]不更改值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37289081/

10-11 00:06