javaarrayspass-by-referencepass-by-valuepass-by-rvalue-reference

Passing only value for private members


I am creating a class with one array as its private member and getter,setter method for that. I want set a value to that array using an array in main function. When I manipulate the array in main function, it should not affect the array present in that class.

I tried this code, but here the array is manipulated

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]);
        }
    }
}

I expect :

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

But the actual output was :

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

Solution

  • You can make defensive copies in ClassB every time you set the array or need to return its values. Like this:

    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);
        }
    }
    

    Side notes:

    Additional readings: