在下面的示例中,我创建了哈希集,我在其中添加了三个字符串值 s1,s2,s3 虽然它显示了哈希集 1 的大小。为什么?
public static void main(String args[])
{
String s1="abc";
String s2=new String("abc");
String s3="abc";
Set setdemo=new HashSet();
setdemo.add(s1);
setdemo.add(s2);
setdemo.add(s3);
System.out.println("s1 hashcode -:"+ System.identityHashCode(s1));
System.out.println("s2 hashcode -:"+ System.identityHashCode(s2));
System.out.println("s3 hashcode -:"+ System.identityHashCode(s3));
System.out.println("Set size is -:"+setdemo.size());
}
输出:
s1 hashcode -:17523401
s2 hashcode -:8567361
s3 hashcode -:17523401
Set size is -:1
最佳答案
Set 不允许重复。当字符串被放入池中时,它们都指向同一个实例。
关于java - 哈希集大小问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15473871/