Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Java in General and the fly likes ArrayList.add overwrites? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "ArrayList.add overwrites?" Watch "ArrayList.add overwrites?" New topic

ArrayList.add overwrites?

Carl Pettersson
Ranch Hand

Joined: Sep 09, 2003
Posts: 73
I use this code

To save the contents of a resultset rs into arraylist result. However, each result.add() overwrites all previous entries with the new one. So I get an arraylist filled with the last record pulled from the db. Why? If I only add() one value, such as add(dbrows[0]), it works fine.
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

You problem is not with ArrayList's add method, its with how you use your dbrows Object array. List.add() just adds an object in the next position in the List. You create one object and add it repeatedly to the list. You need to add different dbrows objects to the list. Otherwise (as you are seeing) every time you change its value, you change it for every occurance in the List.

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Carl Pettersson
Ranch Hand

Joined: Sep 09, 2003
Posts: 73
Ah, thanks.
I agree. Here's the link:
subject: ArrayList.add overwrites?
It's not a secret anymore!