map containsKey与get方法区别经典总结
2015-08-05 10:58
537 查看
</pre><pre name="code" class="html">
前提是:Map可以出现在k与v的映射中,v为null的情况, 所以containsKey出现更加必要
Map集合允许值对象为null,并且没有个数限制,所以当get()方法的返回值为null时,可能有两种情况,一种是在集合中没有该键对象,另一种是该键对象没有映射任何值对象,即值对象为null。因此,在Map集合中不应该利用get()方法来判断是否存在某个键,而应该利用containsKey()方法来判断,例如下面的例子。
下面的代码首先创建一个由HashMap类实现的Map集合,并依次向Map集合中添加一个值对象为null和“马先生”的映射;然后分别通过get()和containsKey()方法执行这两个键对象;最后执行一个不存在的键对象。关键代码如下:
<span style="font-size:18px;">import java.util.HashMap; import java.util.Map; public class TestMapKey { public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(220180, null); map.put(220181, "马先生"); System.out.println("get()方法的返回结果:"); System.out.print("------ " + map.get(220180)); System.out.print(" " + map.get(220181)); System.out.println(" " + map.get(220182)); System.out.println("containsKey()方法的返回结果:"); System.out.print("------ " + map.containsKey(220180)); System.out.print(" " + map.containsKey(220181)); System.out.println(" " + map.containsKey(220182)); } } </span>
执行上面的代码,在控制台将输出如下信息:
get()方法的返回结果:
------ null 马先生 null
containsKey()方法的返回结果:
------ true true false
结论:Map集合中不应该利用get()方法来判断是否存在某个键,因为可能map的key值存在但value的值为null
今天被这个坑了,记录一下
相关文章推荐
- RGB-D 图像 (Semantic Pose using Deep Networks Trained on Synthetic RGB-D)
- The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 51716619E084DAB9
- (FFOS Gecko & Gaia) OTA - Do real check
- Push failed: Failed with error: fatal: Could not read from remote repository.
- hdu1022 Train Problem I 栈的应用
- HDU--5349--2015 Multi-University Training Contest 5--MZL's simple problem
- HDU--5344--2015 Multi-University Training Contest 5--MZL's xor
- Codeforces 443B Kuriyama Mirai's Stones
- 2015 Multi-University Training Contest 5 1009 MZL's Border
- hdu--5347--2015 Multi-University Training Contest 5--MZL's chemistry
- UVALive 3231 Fair Share
- (FFOS Gecko & Gaia) OTA - 进入Gecko层
- taiping
- Cannot delete or update a parent row: a foreign key constraint fails(......)?
- 【HDU2476】【String painter】
- HDU 5352 MZL's City (2015 Multi-University Training Contest 5)
- scala学习记录之trait
- Attempting to initialize hardware acceleration outside of the main thread 处理
- codeforce Gym 100685E Epic Fail of a Genie(MaximumProduction 贪心)
- 2015 Multi-University Training Contest 5 1007