HashMap 没有 getter?
假设我有一个像这样的哈希图
Map map = new HashMap();
map.put(key, p.getText());
,然后要获取一个值,我应该这样做:
map.get("key_value");
有没有办法获取这样的值:
map.key_value;
以加速我的应用程序?
Let suppose that i have a hashmap like this
Map map = new HashMap();
map.put(key, p.getText());
and then to get a value i should do this:
map.get("key_value");
is there a way to get the value like this:
map.key_value;
to speed up my application?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这并不是
Map
真正的工作方式。在 Java 中使用成员运算符 (.
) 进行引用意味着您正在访问变量的公共成员,并且键不会存储为映射的公共成员。That's not really the way a
Map
works. Referencing using a member operator (.
) in Java means you are accessing a public member of the variable, and the keys aren't stored as public members of a map.如果事先知道所有键,您可以扩展 HashMap 并为每个键添加自定义 getter 方法,这样它就能按照您想要的方式工作。但这不会加快程序的执行速度。这一切给你带来的或许只是一点便利。
例如:
If all of your keys are known beforehand, you could extend HashMap and add custom getter methods for each key, such that it would work like you want. But this is not going to speed up the execution of your program. All this buys you is maybe a little convenience.
For example:
您也许可以使用 值
集合
?您可以获得对象的更原始表示,但您仍在使用HashMap
等。但我怀疑它会帮助您加快应用程序的速度,因为这听起来像是一个微小的改进那不会有太大帮助。
无论如何,如果
HashMap
确实是您的瓶颈,也许您想使用其他东西?You might be able to whip something up with the values
Collection
? You can get a more primitive representation of you objects, but you're still working with theHashMap
, etc.But I doubt it will help you speed up your application, as it sounds like a micro-improvement that won't help too much.
Anyway, if the
HashMap
is really your bottleneck, maybe you want to use something else?