我正在创建一个类,其中一个数组作为其私有(private)成员,并为此设置了 getter、setter 方法。我想在 main 函数中使用数组为该数组设置一个值。当我在 main 函数中操作数组时,它不应影响该类中存在的数组。
我试过这段代码,但是这里的数组被操纵了
class ClassB {
private int[] a;
ClassB() { }
ClassB(int[] a) {
this.a=a;
}
int[] geta() {
return this.a;
}
void seta(int a[]) {
this.a = a;
}
}
public class ClassA{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter size : ");
int n = sc.nextInt();
int[] d = new int[n];
System.out.println("Enter array elements : ");
for (int i=0 ; i<n ; i++) {
d[i] = sc.nextInt();
}
final ClassB cb2 = new ClassB(d);
d[3] = 15;
System.out.println("After changing array d : \n Values of array d :");
for (int i=0 ; i<n ; i++) {
System.out.println(d[i]);
}
System.out.println("Values of array a of cb2 :");
int[] b = cb2.geta();
for (int i=0 ; i<n ; i++) {
System.out.println(b[i]);
}
}
}
我希望:
Enter size :
5
Enter array elements :
1
2
3
4
5
After changing array d :
Values of array d :
1
2
3
15
5
Values of array a of cb2 :
1
2
3
4
5
但实际输出是:
Enter size :
5
Enter array elements :
1
2
3
4
5
After changing array d :
Values of array d :
1
2
3
15
5
Values of array a of cb2 :
1
2
3
15
5
最佳答案
每次设置数组或需要返回其值时,您都可以在 ClassB
中制作防御性副本。像这样:
class ClassB {
// ... code omitted for brevity
ClassB(int[] a) {
seta(a);
}
int[] geta() {
int[] copy = new int[a.length];
System.arraycopy(a, 0, copy, 0, a.length);
return copy;
}
void seta(int a[]) {
this.a = new int[a.length];
System.arraycopy(a, 0, this.a, 0, a.length);
}
}
旁注:
- 如果你真的想让
ClassB
不可变,你不应该为它的值设置一个 setter。 - 实用程序
System.arraycopy
用于创建数组的副本。在这里随意使用更适合您的需求(您可能想考虑使用a.clone()
...这是一个很好的主题:Why clone() is the best way for copying arrays?)。
补充阅读:
关于java - 只为私有(private)成员传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56233144/