1

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 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.