//equals():就是直接比较对象的内存地址(==) //另外在看源码的过程中还注意到一个注释:当需要重写equals方法时,必须要重写HashCode方法,因为相等的对象必须具有相等的哈希代码。 /** Note that it is generally necessary to override the {@code hashCode} * method whenever this method is overridden, so as to maintain the * general contract for the {@code hashCode} method, which states * that equal objects must have equal hash codes. */ publicbooleanequals(Object obj) { return (this == obj); } //hashCode():返回对象的JVM内存地址 publicnativeinthashCode();
privateint hash; // Default to 0 // final修饰,因此String的内容也是不变的 privatefinalchar value[];// The value is used for character storage. publicinthashCode() { inth= hash; if (h == 0 && value.length > 0) { char val[] = value;
for (inti=0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; }
// 在没有创建相同字符串的情况下,下面会创建几个String对象? Strings1=newString("Sean Blog Site: https://code666.top"); Strings2=newString("Sean Blog Site: https://code666.top");
两个?恭喜你答错了!答案是三个。
第一个是字符串常量池中Sean Blog Site: https://code666.top,另外两个就是堆内存创建的Stirng对象咯。所以应该是三个