views:

18

answers:

1

I'm not sure what is wrong but there's some weird happening in my Paint() concerning some variables.

this code works just fine:

public void paint(Graphics g)
{
    Point[] positions = {new Point(20,50),new Point(60,30),new Point(80,20),new Point(80,30)};
}

but this one don't, i wanted this one, because im changing position formations on user's selection:

// declared somewhere
Point[] selectedFormation = {new Point(20,50),new Point(60,30),new Point(80,20),new Point(80,30)};

public void paint(Graphics g)
{
    Point[] positions = selectedFormation;
}
A: 

when you do positions = selectedFormation you are not creating a copy of selectedFormation, you are just storing a reference of it into position. Both point to the same object (the same array). If the array is changed by using position, it is the same array as selectedFormation.
Use clone() to create a copy of the array:

public void paint(Graphics g)
{
    Point[] positions = selectedFormation.clone();
}

but consider that clone does not copy the elements of the array, both list will contain the same instances. If you only change the coordinates of any point, it will affect both lists. In that case you need to make a deep copy of the list:

public Point[] deepCopy(Point[] array) {
    Point[] copy = new Point[array.length];
    for (int i = 0; i < array.length; i++) {
        copy[i] = new Point(array[i]);
    }
    return copy;
}

could use generalization for this... but lets keep it simple

Carlos Heuberger
Thank you, im now using ArrayCopy, do you think this is the best way?
Clave
not sure what ArrayCopy is... or do you mean `System.arraycopy(...)`?
Carlos Heuberger
yup, but i switched to you deepCopy :) thank you very much!
Clave