Ubaby Ubaby - 1 month ago 7
Java Question

Why last array filled with first array without asking?

I try to hold some value in 1st array, then another value in 2nd array, I try to print 1st array and it returns 2nd array values. Any ideas why ?

this is main method to call program

public class testC
{
public static void main(String[] args)
{
groupC trial = new groupC();
trial.setCol(10, 10);
}
}


this is class calls another class to get color and fill in array each new coordinate

public class groupC
{
private color1 col = new color1();
private int[] cola1 = new int[3];
private int[] cola2 = new int[3];

public groupC()
{

}

public void setCol(int xIn, int yIn)
{
cola1 = col.getCol(xIn, yIn);
System.out.println(cola1[0] + " " + cola1[1] + " " + cola1[2]);
/* try next color depending on 1st */
cola2 = col.getCol(xIn + 100, yIn + 100);
System.out.println(cola2[0] + " " + cola2[1] + " " + cola2[2]);

System.out.println("this is 1st color, but why now the same as 2nd ?" + cola1[0] + " " + cola1[1] + " " + cola1[2]);
}
}


this is class, which simply gets coordinate and return array of color values at that point

import java.awt.Color;
import java.awt.Robot;
import java.awt.AWTException;

public class color1
{
int[] color = new int[3];

public color1()
{
}

public int[] getCol(int xIn, int yIn)
{
// accepts position of color, returns size 3 array of red green blue
// integers
try
{
Robot r = new Robot();
Color x = r.getPixelColor(xIn, yIn);
color[0] = x.getRed();
color[1] = x.getGreen();
color[2] = x.getBlue();
}
catch (AWTException e)
{
e.printStackTrace();
}
return color;
}
}

Answer

Because color1 reuses a single array:

public class color1
{
    int[] color = new int[3]; // <== Creates one array for this color1 instance
    // ...
}

All that happens in getCol is that it gets filled in (again):

Color x = r.getPixelColor(xIn, yIn);
color[0] = x.getRed();   // <==== Nothing here is creating a new color array
color[1] = x.getGreen();
color[2] = x.getBlue();

If you want to use more than one array, you have to actually create more than one array. That would probably mean removing the color instance member entirely, and creating the array in getCol:

import java.awt.Color; import java.awt.Robot; import java.awt.AWTException;

public class color1
{
    public color1()
    {
    }

    public int[] getCol(int xIn, int yIn)
    {
        // accepts position of color, returns size 3 array of red green blue
        // integers
        int[] color = new int[3]; // Has to be here because of how you're (not) handling exceptions
        try
        {
            Robot r = new Robot();
            Color x = r.getPixelColor(xIn, yIn);
            color[0] = x.getRed();
            color[1] = x.getGreen();
            color[2] = x.getBlue();
        }
        catch (AWTException e)
        {
            e.printStackTrace();
        }
        return color;
    }
}
Comments