开发者

Java array rewrites all indexes

First of all, my problem is pretty much the same as described there: Array returning same values for all indexes except it's for Java and not C#. (Which I heard were pretty similar however)

A few classes are in play here, I will try to give out the most details:

SomeInterface: An interface for different types of pixels.

PixelTypeA: One type of pixel.

PixelTypeB: Another type of pixel.

(PixelTypeA and PixelTypeB implement/inherit from SomeInterface)

PixelImage: That's the problematic class, it contains the two-dimensionnal array that has the same values for all squares in it, here is the declaration:

SomeInterface[][] pixels;

Now, the constructor does the following to allocate memory (height and width are parameters):

pixels = new SomeInterface[height][width];

So far so good. But then, a method in PixelImage is called to load pixels from a PPM file. That code works correctly because if I test the value of a pixel right after it's saved in memory (in the readfile loop), it is alright. However, I realized that after each loop iteration (i.e. after saving each pixel in memory), all the values of the pixels array have the same value, and that is the value of the last pixel saved. Here is the important code in the loop:

pixels[row][col] = new PixelTypeA( pixelValue );

As I said, if I do a system print of pixels[row][col] on the next line, it has the right value in it, though every other index in the pixels two-dimensionnal array has that value too. row and col get incremented correctly. I'm quite new to Java and my assumption is that I missed something regarding references or something of the like, which is causing me to update all of the pixe开发者_如何学Gols array accidentally at each iteration of the readfile loop (or might it be the declaration/initialization that is the problem?). I tried to solve this by myself for several hours, but this has become really frustrating. I changed the names and cannot give you complete code since this is an assignment and I want to do it by myself, I just need clues as what might cause that weird behaviour right now.

Thank you!


You most likely reuse the object you insert in the array, instead of doing a new every time.

This mean that every array entry points to the same object which is set to the latest value read.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜