学习 HashMap
我正在学习如何使用 hashMaps,有人可以检查我编写的这段代码并告诉我它是否正确吗?我的想法是拥有一个在公司工作的员工列表,我想从 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);
}
}
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 in 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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的课程中,您需要更改/添加如下内容:
正确使用
HashMap
。请注意,
addStaff(
) 和removeStaff()
对于大多数用途来说不太有用,因为它们仅添加和删除一名工作人员“Joe”。一种更有用的处理方式是Map 与其他数据结构的不同之处在于它有一个“键”,可以让您检索一个项目。如果您事先没有该项目的密钥,则无法以提高性能的方式使用
Map
。请注意,除了返回相同 hashCode 的相等项之外,HashMap 还要求键正确遵循相等规则。基本上,如果一个对象
a
和另一个对象b
被认为是相等的,那么hashCode()
部分就超出了简单的相等性,并且是必需的使HashMap
正常工作。In your class, you need to change / add things to look like:
to use a
HashMap
properly.Note that
addStaff(
) andremoveStaff()
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 beWhat 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 aMap
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 objecta
and another objectb
are considered equal, thenThe
hashCode()
part is above and beyond simple equality, and is required for theHashMap
to work correctly.对我来说看起来不错,但是我会创建一个 Employee 类并为每个员工使用唯一的 id。
这样您就可以随意扩展员工信息,而无需重新定义员工地图。也永远不要假设人类的名字是独一无二的。
Looks good to me, however I would have created a Employee class and use a unique id for each staff member.
This way you can extend the staff info at will without redefining your staff map. Also never assume that human names are unique.
首先请阅读此内容
http://download.oracle.com/javase/6 /docs/api/java/util/Map.html
很多事情对你来说会更加清晰。
然后查看此处的一些示例:
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: