Unable to get correct values from array

Viewed 32

So when i set an array and print out the values, they are correct. But when printing it out from my get array method, they are wrong.

public void setArrOfCols(BufferedImage bi){
    for(int i = 0; i < this.arrOfCols.length; i++){
        int value = bi.getRGB(i, 0);
        int red = (value >> 16) & 0xff;
        int green = (value >> 8) & 0xff;
        int blue = value & 0xff;
        int alpha = (value >> 24) & 0xff;
        
        this.arrOfCols[i] = new Pixel(red, green, blue, alpha, i, 0);
    }
    String retStr = "";
    
     for(int i = 0; i < this.arrOfCols.length; i++){
        retStr += this.arrOfCols[i].getRed() + " "
                + this.arrOfCols[i].getGreen() + " "
                + this.arrOfCols[i].getBlue();
        retStr += "\n";
    }
    System.out.println(retStr + " TestSet");
}

public Pixel[] getArrOfCols(){
    String retStr = "";
    
     for(int i = 0; i < this.arrOfCols.length; i++){
        retStr += this.arrOfCols[i].getRed() + " "
                + this.arrOfCols[i].getGreen() + " "
                + this.arrOfCols[i].getBlue();
        retStr += "\n";
    }
    System.out.println(retStr + " testGet");
    
    return this.arrOfCols;
}

Is it a possible pass by reference issue? Both outputs should be the same:

16 43 62
70 73 48
39 61 85
42 65 81
64 75 79
113 106 85
TestSet
103 148 190
103 148 190
103 148 190
103 148 190
103 148 190
103 148 190
testGet
2 Answers

You shared two public methods, which in itself seems fine. I can't reproduce the same output as you, but I would recommend you two things, which might solve the problem for you.

  1. rename the first method to readImage
  2. Make the second method return a copy of the array, other methods might tinker with it and hence you experience some strange behaviour.
return Arrays.copyOf(this.arrOfCols, this.arrOfCols.length);

The .getRed() and other color methods were getting colors from a different image

Related