如何传递整个地图
有另一个问题。
我试图发送对象及其关联键的整个映射,以便可以从另一个类访问它。我使用的方法不起作用,因为我尝试使用与传递数组列表相同的方法,但它不适用于 Map。
正确的做法是什么?
这是我尝试过的
public Map <Integer, Employee> getAllEmps()
{
return (Map <Integer, Employee>) ;
}
,这就是我声明它的方式(实际地图本身)
private static Map <Integer, Employee> employeeMap = new TreeMap<Integer,Employee>();
got another issue.
Im trying to send an entire Map of objects and their associated keys so that it can be accessed from another class. The method I am using does not work, as I tried to use the same method that is used to pass an array list, but it does not work for a Map.
what would be the correct way of doing it?
this is what I have tried
public Map <Integer, Employee> getAllEmps()
{
return (Map <Integer, Employee>) ;
}
and this is how I have declared it (the actual map itself)
private static Map <Integer, Employee> employeeMap = new TreeMap<Integer,Employee>();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以返回变量本身:
这将允许任何人修改地图的内容。
为了防止修改,您可以返回一个不可修改的Map:
或者,您可以返回一个副本:
You can return the variable itself:
Which would allow anyone to modify the contnent of the map.
To prevent modification, you can return an unmodifiableMap:
Alternatively, you can return a copy:
您必须返回地图实例,而不是类型。
如果您只想要员工(没有钥匙),您可以添加另一种方法
You have to return the map instance, not the type.
If you want only the employees (with no keys) you can add another method
为什么不尝试传递变量本身并将映射作为成员变量呢?
Why don't you try passing the variable itself and have the map as a member variable?
你的 getAllMaps() 函数需要实际返回一个地图;你的意思是返回静态的employeeMap?
Your getAllMaps () function needs to actually return a map; do you mean it to return the static employeeMap?