为什么我可以使用字符串作为HashMap中的键? [英] Why can I use Strings as keys in a HashMap?

查看:76
本文介绍了为什么我可以使用字符串作为HashMap中的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果相同的两个 String s实际上并不相同,那么为什么我可以在 HashMap 字符串对象

 字符串s1 = 测试; 
String s2 =测试;

System.out.println(s1 == s2); //应该是false
System.out.println(s1.equals(s2)); //应该是true

HashMap< String,String> map = new HashMap();
map.put(s1,foo);
System.out.println(map.get(s2)); //应该是foo - 但为什么?

对于 HashMap code> String objects?如果没有,为什么可以使用两个不同的字符串来放置并从哈希中获取值?

解决方案

HashMap 通过调用 equals() hashCode()来比较对象。
字符串将覆盖这些方法以按值进行比较。


If two Strings that are the same are not actually identical, then why can I use strings as keys in a HashMap without using the same String object?

String s1 = "Test";
String s2 = "Test";

System.out.println(s1 == s2); // should be false
System.out.println(s1.equals(s2)); // should be true

HashMap<String, String> map = new HashMap();
map.put(s1, "foo");
System.out.println(map.get(s2)); // should be "foo"--but why?

Does HashMap have some special behavior for String objects? If not, why can two "different" strings be used to put and to get values from a hash?

解决方案

HashMap compares objects by calling equals() and hashCode().
String overrides these methods to compare by value.

这篇关于为什么我可以使用字符串作为HashMap中的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆