简体   繁体   中英

Strange array behaviour in Java

I'm been doing some Java coding lately and encountered this very strange problem. I wrote a class in Java that extends JPanel and resizes objects withing itself depending on its size.

For better understanding I reduced the problem to the smallest possible code.

The thing is, when I run the code following below, it would always not only set array1[0] but also set array2[0] . I don't understand why array2 changes, even though I never made it change...

I added a little to highlight what operation I think the code does, that I can't see.

When I run the code and resize the the window, the value printed out will rapidly change and be infinity just after a little movement.

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class Beispiel extends JPanel {

    double[] array1, array2;

    public Beispiel(double[] array){
        array1 = array;
        array2 = array;
    }

    public void repaint(){
        try {
            array1[0] = array2[0]*this.getWidth();
            System.out.println(array2[0]);
            // array2[0] = array1[0]   <--- what i think it does
        } catch(Exception e){
        }
    }

    public static void main(String[] args){
        JFrame frame = new JFrame();
        frame.setSize(300,200);
        frame.setLayout(new BorderLayout());

        double[] array = {1.0,3.0};

        frame.add(new Beispiel(array));

        frame.setVisible(true);
    }
}

array2 does change. When you use array1 = array and array2 = array , you're making array1 and array2 refer to the same array. So any change made to array1 will be reflected in array2 as well.

To solve this problem, use java.util.Arrays.copyOf(array, array.length) or array.clone() (note that this returns a shallow copy of the array, however).

Instead of doing this,

public Beispiel(double[] array){
    array1 = array;
    array2 = array;
}

Try doing this and share the results

public Beispiel(double[] array){
    array1 = Arrays.copyOf(array, array.length);
    array2 = Arrays.copyOf(array, array.length);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM