yasuo
yasuo

Reputation: 37

Private array change values after passing to another class - java

I have 2 classes. Class1 and Class2. In Class1 I create a private double tempPoint[] variable and I set some values. After passing this variable to Class2 and change the values of tempPoint[] inside Class2, the values of tempPoint[] changes in Class1 too. How can I avoid that?

Main:

public class Main {

public Main() {
    // TODO Auto-generated constructor stub
}

public static void main(String[] args) {

    Class1 newclass= new Class1();
    newclass.method1();

}

}

Class1:

public class Class1 {

private double tempPoint[] = new double[1];
private Class2 class2;

public Class1() {
    class2 = new Class2();
}

public void method1(){

    tempPoint[0] = 100;

    System.out.println(tempPoint[0]);

    class2.method2(tempPoint);

    System.out.println(tempPoint[0]);

}

}

Class2:

public class Class2 {

public Class2() {
    // TODO Auto-generated constructor stub
}

public void method2(double[] point){


    point[0] = 0;


}

}

Output:

100.0
0.0

Upvotes: 0

Views: 54

Answers (1)

wero
wero

Reputation: 33000

You need to pass a copy of the array if you want to be sure that nobody changes the content of the original array:

class2.method2(tempPoint.clone());

Upvotes: 3

Related Questions