This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes reference does not work Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "reference does not work" Watch "reference does not work" New topic
Author

reference does not work

nimo frey
Ranch Hand

Joined: Jun 28, 2008
Posts: 580
I have this:



So why does way 2 works and way 1 not ??
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14278
    
  21

With way 1, you are creating a new Person object and you make the variable p refer to that new object, if p was null (because the entry in the map with the key "men" wasn't in there).

Just making variable p refer to something else does not change anything in the map. There is no link between variable p and the entry in the map.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
nimo frey
Ranch Hand

Joined: Jun 28, 2008
Posts: 580
okay thanks,


I have thought that the "link" is achieved by this:


but I was wrong.

So the only solution is way 2.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
That latter code snippet gets out of your Map what you earlier put in under "men".

I presume you are getting the Map as a return value from the getPersonByGroup() method, in which case that method is very inappropriately named. Why isn't the Map a field of the class?
nimo frey
Ranch Hand

Joined: Jun 28, 2008
Posts: 580
Sorry I have write the method not completly:

The map "personByGroup" is a field of a Object called Users:



and p is obtained by this reference:



So you see the Map is a field of the class Users.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
That shows how confusing it is if you don't post real code. And I still don't like personByGroup as a field name.
Sean Clark
Rancher

Joined: Jul 15, 2009
Posts: 377

Hey,
I think you might be best to post both the Person and User classes so we can see how they link. That's just confusing.


I love this place!
 
wood burning stoves
 
subject: reference does not work