Learning HashMap
I'm just learning myself how to use hashMaps, can someone check this piece of code I have written and tell me if it's correct? The idea is to have a list of staff working i开发者_如何学编程n a company, I want to add and remove staff from a hashMap.
public class Staff
{
private HashMap<String, String>id;
public Staff(String name, String number)
{
id = new HashMap<>(name,number);
}
public addStaff()
{
id.add("Joe","1234A2);
}
public removeStaff()
{
id.remove("Joe","1234A2);
}
}
In your class, you need to change / add things to look like:
private HashMap<String, String> id;
public Staff(String name, String number)
{
id = new HashMap<String, String>();
}
public addStaff()
{
id.put("Joe","1234A2");
}
public removeStaff()
{
id.remove("Joe");
}
to use a HashMap
properly.
Note that addStaff(
) and removeStaff()
are not likely to be very useful for most purposes because they only add and remove the one staff member "Joe". A more useful way of doing things would be
public void addStaff(StaffMember member) {
id.put(member.getName(), member);
}
public StaffMember get(String name) {
// this will return null if the member's name isn't a key in the map.
return id.get(name);
}
What makes a Map
different from other data structures is that it has a "key" which allows you to possibly retrieve one item. You cannot use a Map
in the ways that give you a boost in performance if you don't have the item's key beforehand.
Note that HashMap
s require keys to follow the rules for equality correctly in addition to equal items returning the same hashCode. Basically if on object a
and another object b
are considered equal, then
// Reflexive property
a.equals(a) must return true
// Symmetric property
if (a.equals(b)) then b.equals(a) must return true
// Transitive property
if (a.equals(b) and b.equals(c)) then a.equals(c) must return true
// Additional requirements to make hash related algorithms work properly
a.hashCode() == b.hashCode() // must be true
The hashCode()
part is above and beyond simple equality, and is required for the HashMap
to work correctly.
Looks good to me, however I would have created a Employee class and use a unique id for each staff member.
class Employee {
Integer id;
String name;
}
Map<Integer, Employee> staff = new HashMap<Integer, Employee>();
This way you can extend the staff info at will without redefining your staff map. Also never assume that human names are unique.
First of all please read this http://download.oracle.com/javase/6/docs/api/java/util/Map.html and a lot of things will be more clear for you. Then take a look here for some samples:
- http://www.java-samples.com/showtutorial.php?tutorialid=369
- http://www4.ncsu.edu/~kaltofen/courses/Languages/JavaExamples/jgl3.1.0/doc/api/com.objectspace.jgl.examples.HashMapExamples.html
精彩评论