`
harry
  • 浏览: 180125 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

该选择哪个Java Map对象?

    博客分类:
  • Java
阅读更多

HashMap, Hashtable, LinkedHashMap and TreeMap are all classes implementing the Map interface. All of them will have keys and values. The keys are unique. To find out whether the keys are same, they make use of the equals() method.
So, let us look at each one of them:

HashMap

HashMap is not sorted or ordered. If you just need a Map, and you don’t care about the order of the elements while iterating through it, you can use a HashMap. That keeps it simple. The values can be null. But the key should ne unique, so you can have one null value for key. (Allows only one null key).

Hashtable

Hashtable is almost the same as HashMap. The main differences are:
1. Hashtable does not let you have null value for key.
2. The key methods of Hashtable are synchronized. So, they may take a longer time to execute, compared to HashMap’s methods.

LinkedHashMap

LinkedHashMap will keep the order in which the elements are inserted into it. If you will be adding and removing elements a lot, it will be better to use HashMap, because LinkedHashMap will be slower to do those operations. But, you can iterate faster using LinkedHashMap. So, if you will be iterating heavily, it may be a good idea to use this.

TreeMap

TreeMap is a sorted Map and will be sorted by the natural order of the elements. If you want, you can define a custom sort order by means of a Comparator passed to the constructor. So, when you need a custom sort order, it is clear which class you should be using!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics