Search code examples
javaarraysequality

two arrays are always equal


I have this code

for (int i=0; i<tini.length; i++){
    tini[i].tempLabel.setText("Temp: "+ Float.toString(tempArray[i]) +"°" );
    out_status[i] = tini[i].alarm;
    frame.statusLabel.setText("Connetction: OK, String: OK");
}

System.out.println("old: " + Arrays.toString(out_status_old));                  
System.out.println("new: " + Arrays.toString(out_status));
if (Arrays.equals(out_status, out_status_old) ){
    System.out.println("UGUALI");
}

out_status_old = out_status;

the resulting arrays are always equal. I cannot understand the reason. Using a Button in JFrame, in a GUI interface i can modify the value of alarm, but both the old value and the actual one change at the same time!


Solution

  • The line out_status_old = out_status; does not create a copy of the array. You have just two variables, out_status and out_status_old, pointing to the same array.

    If you want to create a proper copy of the array, you can e.g. use Arrays.copyOf (or one of its variants).