• Post Reply Bookmark Topic Watch Topic
  • New Topic

ArrayList boo boo :(  RSS feed

 
Kaif Ahmed
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello again,

Before I start just want to say, this forum has been really halpful so far, thanks guys!

So what's wrong now? My ArrayList wont play with me anymore.

For this code assume the naughty ArrayList is "GlobalDataStore.FaceList" which is an ArrayList of type "face". What's in face? Nothing much, just a string and 4 int variables (name, x, y, width, height).

"DetectedFace" is an object of type "face" which is just used temporarily move stuff over to the ArrayList.




Problem with all this is that while i'm inside the for loop it seems to be adding everything to the ArraryList correctly. I can read the individual values from different positions in the array, it's all correct.

As soon as I get out of that for loop however, all the values in the arraylist are the same... that is every position in the array is the same object.

I reckon I'm reading from the arraylist incorrectly, I'm not sure what else could be wrong.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's only a single DetectedFace object, which you add to the ArrayList numFaces times. You're changing its member data each time through the loop. It will end up with the last set of values you put into it. You need to create a new DetectedFace object at the top of each loop iteration, so the ArrayList is a list of separate objects, not many references to the same object.

I bet you would greatly benefit from reading this and especially this.
 
Rashid Mayes
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is because you are changing members of the same instance of DetectedFace which *appears* to be static. You will need to change the code to something like this:

 
Kaif Ahmed
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aha, that solved it. Thanks guys! I'll have a look at those articles Ernest, I need to learn a bit more about it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!