my dog learned polymorphism*
The moose likes Beginning Java and the fly likes hashmaps Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "hashmaps" Watch "hashmaps" New topic
Author

hashmaps

Bron Czimes
Ranch Hand

Joined: May 09, 2004
Posts: 44
hi there
i'm not sure whether i'm in the right place here but i have a few questions about hashmaps.
can you put whole objects into them?
I have tried creating a hashmap that puts a field from an object as the key, and the whole object itself as the value, but I keep getting an error. I've never used hashmaps before so I'm not sure whether its the hashmap or some other mistake....

is this correct, or am i totally down the wrong path?
Bron
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
can you put whole objects into them?
Yes. Objects are used for the keys and values.
I keep getting an error
What error? Is it a compiler error? What is it? Is it a runtime error? What is it?
What does the Passenger class definition look like? What does getSeat() return? Is it a primitive value, or an object reference? Primitive values cannot be used as hash map keys.
If you're looking to build an understanding of how the hash map data structure works, I suggest taking a look at Chapter 12 Section 3 of David J. Eck's Introduction to Programming Using Java.
[ May 11, 2004: Message edited by: Dirk Schreckmann ]

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Bron Czimes
Ranch Hand

Joined: May 09, 2004
Posts: 44
lol sorry, forgot to put the error on there! silly me
i get a compile error:
put(java.lang.Object, java.lang.Object) in java.util.Map cannot be applied to (int, Passenger)
passengMap.put(bPassenger.getSeat(),bPassenger);
which I think means that int is wrong coz its a primitive. is that right?
Passenger class has the fields passenger name (string), passenger age(int), passenger gender(string), and seat number(int). Its for an airline reservation system. (Don't ya just love uni assignments!! yay!)
If i made the seat number a String, would it work?
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Yes, Strings are objects.
You could also wrap the primitive int in an Integer object.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: hashmaps
 
Similar Threads
Populating HashMaps of HashMap of Objects
This is ugly, but would it cause a leak (or other problem(s))?
reading strings with readLine
child threads calling methods in master class
Problem going from 1.5 to 1.4.2