It's not a secret anymore!*
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 OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA 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: 14117
    
  16

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 7 API documentation
Scala Notes - My blog about Scala
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: 38519
    
  23
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: 38519
    
  23
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!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: reference does not work