Hashmaps
how can i get a hashmap to hold a key as well as an object...
for example
i define the hashmap:
private HashMap<String, House> stock;
then the constructor is:
stock = newHashMap<String, Car>();
if i want to make a method that is:
public void addHouse(String number, String road, int Price)
how do i make my hashmap have the number as the key and the house as the object?thank you
First, when you said "Car" I assume you meant "House."
Not knowing what House is, I can only take an educated gues at one possible way to do it:
House house = new House(number, road, price);
map.put(house.getAddress(), house);
When you post code, please use[code] and [/code] tags as described in [url=http://forum.java.sun.com/help.jspa?sec=formatting]Formatting tips[/url] on the message entry page. It makes it much easier to read.
public void addHouse(String number, String road, int Price) {
stock.put(number, new House(number, road, price));
}
I would rather write it:
public void addHouse(House house) {
stock.put(house.getKey(), house);
}
That way, if the attriubutes of house change, this class is unaffected.
Also, subclasses of house could be added.