作者:宝蓝小礼服 | 来源:互联网 | 2022-12-10 12:20
我用字符串文字创建了3个字符串2,使用new创建了一个字符串2.但是当我为它们打印哈希码时,它会给出相同的哈希码.我很困惑它如何返回相同的哈希码.请找到以下示例.
public class StringTest
{
public static void main(String[] args)
{
String str = "abc";
String str1 = "hfdjkfhs";
System.out.println("hashValue str:::" + str1.getClass().hashCode());
System.out.println("hashValue str:::" + str.getClass().hashCode());
String str2 = new String("def");
System.out.println("hashValue:::" + str2.getClass().hashCode());
}
}
输出: -
hashValue str1 ::: 366712642
hashValue str ::: 366712642
hashValue str2 ::: 366712642
1> Jorj..:
您正在打印String
类的哈希码,而不是打印创建的String
对象.
代替:
str.getClass().hashCode()
你应该有:
str.hashCode()