GeeCON Prague 2014*
The moose likes Java in General and the fly likes ArrayList added in to a map behaves in strange manner 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 added in to a map behaves in strange manner" Watch "ArrayList added in to a map behaves in strange manner" New topic
Author

ArrayList added in to a map behaves in strange manner

veena sasikumar
Greenhorn

Joined: Nov 27, 2006
Posts: 29
Hi,

I have experienced a strange problem. TreeMap behaves in a strange way and my doubts are mentioned at the bottom of the mail. Sorry for including the long code.I thought the problem will not be clear without the code.


My doubts

1) When I put something in a map, the results shows that the get(Object key) method of map returns just a reference. That is no additional objects will be created for the objects put inside a map, though we get the objects from the map and assigns to some reference. Is this correct?

2) When I change the the values of first object in the ArrayList (currentRSValueArray = (long []) dailyTransObjectArray2.get(0) and changed the values of "currentRSValueArray" , why did the same change happen for the other objects in the ArrayList. It is found that when I used dailyTransObjectArray1.add(j, new long[6]) instead of dailyTransObjectArray1.add(j, blankRSValueArray), this didn't happen.Could you please explain this behaviour.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
This has nothing to do with the Map at all.

What is happening is that you only create one array (which is an object, too).

You let each "slot" in the ArrayList reference that same array. So no matter from which slot you later get the array back, you will of course see the same changes.

Does that help?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
veena sasikumar
Greenhorn

Joined: Nov 27, 2006
Posts: 29
Hi Ilja Preuss,

Thanks for the reply...

I was thinking in a different way. When we add arraylist in to map, I thought the added item will behave as a different object.

Now it is clear.

Thanks once again
veena
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Think of it as putting the *reference to* the ArrayList into the Map.
 
GeeCON Prague 2014
 
subject: ArrayList added in to a map behaves in strange manner