如何调用 hashmap 和 hashmap java中其他类的值?
我想创建 5-6 个类,我将值存储在第一类和第二类的哈希图中。我想从 4 号、5 号和 5 号开始称呼它。第六课。如何获取任何片段或示例来实现这一点将会有所帮助,谢谢
I would like to create 5-6 classes,I am storing values in hashmap in 1st class & I would like to call it from 4th,5th & 6th class.How to get this any snippets or example to implement this will be helpful,Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
两种合理的做法。
为地图提供一个公共 getter。 Class5 将调用 class1.getMap().doSomething()。没有太多工作(好的),并且外部类可以对地图做任何他们想做的事情,例如clear(),这可能会或可能不会好。
为地图编写单独的方法,例如 putIntoMap()、removeFromMap() 等。需要更多工作,但您可以限制外部人员可以执行的操作。如果您不希望它们能够clear(),请不要编写ckearMap() 方法。
纯粹主义者有一条“德米特法则”,规定总是选择选项 2,但恕我直言,这往往是矫枉过正。
Two reasonable approaches.
Have a public getter for the Map. Class5 would the call class1.getMap().doSomething(). Not much work (good) and outside classes can do anything they want to the map, e.g. clear(), which may or may not be good.
Write individual methods for the map, e.g. putIntoMap(), removeFromMap(), etc. More work but you can restrict what outsiders can do. If you don't want them able to clear(), don't write a ckearMap() method.
Purists have a "Law of Demeter" that says always do option 2 but IMHO that is often overkill.
您应该对哈希图使用 setter 和 getter。
you should use setters and getters for the hashmap.