Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashmaps

 
Bron Czimes
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Bron Czimes
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, Strings are objects.
You could also wrap the primitive int in an Integer object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic