Difference between Pair and Hashmap?

青春壹個敷衍的年華 提交于 2020-02-04 03:47:47

问题


What is the necessity to introduce Pair class when Hashmap can do the same job?

I see Pair being introduced to Java version 8


回答1:


Your choice of which class to use is not just a message to your computer. It's also a message to future developers - people who will maintain your code in the future, or even you yourself in a few months time.

By choosing whether to declare a particular variable as either HashMap or Pair, you're telling those future developers something. It's EITHER

This variable references some kind of map, which uses a hash algorithm for fast retrieval.

OR

This variable references a pair of values.

That will help the future developers to understand what your code is doing. Whereas you can certainly use a HashMap with a single entry instead of a Pair, it would be a very strange thing to do, and it would send entirely the wrong message to the future maintainers of your code.




回答2:


Pair<K, V> is a part of JavaFX whereas Hashmap is in the core API. You can most likely use Pair to create a hashmap implementation (I have not tested this, but I see no reason as to why not), but a Pair is not the same as a HashMap.



来源:https://stackoverflow.com/questions/45396342/difference-between-pair-and-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!