0

I have a BCD class with a constructor inside, and created a BCD object called 'b' from myArray. When I alter myArray, why does Java change b as well, and how do I make the two 'independent', like when I change myArray after the declaration, b stays constant?

public class BCD{
    private int digits;
    BCD(int[] digitArray){
        digits = digitsArray;
    public int nthDigit(int n) {
        return digits[n];
    }
    //more methods
   
    public static void main(String[] args) {
        int[] myArray = {1,2};
        BCD b = new BCD(myArray);
        myArray[1]=3;
        System.out.println(b.nthDigit(1));

}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
PyCoder
  • 11
  • 3
  • 3
    you need to clone the array. – Juvanis Mar 05 '21 at 15:40
  • 2
    BTW: `digitArray = digits;`cannot be correct, isn't it `digits = digitArray;`? (and assignment does not copy values inside the array, it just make left variable contain same object as right) –  Mar 05 '21 at 15:44
  • 1
    The code, as written in the question, does not compile. – Abra Mar 05 '21 at 15:46
  • @user15244370 – Äh no, that's wrong, at least the second part of the sentence! Correct is: it just makes the left variable referring to the same object as that one on the right. – tquadrat Mar 05 '21 at 15:48
  • @user15244370 – Sorry, but no! If you want to use "contain" with a variable, it is still the reference to an object that it contains, not the object itself. This lack of precision in wording it the reason for questions like this one! – tquadrat Mar 05 '21 at 15:52
  • Is it possible to not clone the array? – PyCoder Mar 05 '21 at 16:54

2 Answers2

1

Clone the array.

int[] a = {1,3};
int[] b = a.clone();
a[1]=33;
System.out.println(a[1]);
System.out.println(b[1]);
the Hutt
  • 16,980
  • 2
  • 14
  • 44
0

You passed a object reference to that constructor because of that all modification done to that object will be reflected to those holds reference of that object.

Anand Kumar
  • 156
  • 7