jeudi 12 mars 2015

Java - strange Array behaviour



im 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 dont understand why array2 changes, even though i never made it to change...


i added a little comment line what operation i think the code does, that i cant see.



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


}




Aucun commentaire:

Enregistrer un commentaire