该选择哪个Java Map对象?

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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值