为什么答案是 3? 不是2么?
package test;
import java.util.HashSet;
public class Test {
private String str;
public Test(String str) {
this.str = str;
}
@Override
public int hashCode() {
int hascode = this.str.hashCode();
return hascode;
}
@Override
public boolean equals(Object obj) {
return this.str.equals(obj);
}
public static void main(String args[]) {
Test h1 = new Test("1");
Test h2 = new Test("1");
String s1 = new String("2");
String s2 = new String("2");
HashSet
r**e 发帖数: 226
2
i see. the equals method is wrong...
c******r 发帖数: 5
3
Correct me if I am wrong.
String objects are immutable- which means they physically cannot be changed.
Therefore, no matter how many instance you create (with the same content),
they all "reference" to the same object in the heap.
g**e 发帖数: 6127
4
wrong. Strings are immutable, but they may not refer to the same object.
String a = "abcd";
String b = new String("abcd");
String c = "ab" + "cd";
String tmp = "ab";
String d = tmp + "cd";
is a==b==c==d?
this is a very typical interview question.
Also make sure you know the concept of String Literal, as well as what
String.intern() does.
Also know what is StringBuffer and StringBuilder, what are their differences.
Then you won't have any problem answering string interview questions in Java.
changed.
,
【在 c******r 的大作中提到】 : Correct me if I am wrong. : String objects are immutable- which means they physically cannot be changed. : Therefore, no matter how many instance you create (with the same content), : they all "reference" to the same object in the heap.
g**e 发帖数: 6127
5
我觉得版主应该给我个包子,写了这么多
differences.
Java.
content)
【在 g**e 的大作中提到】 : wrong. Strings are immutable, but they may not refer to the same object. : String a = "abcd"; : String b = new String("abcd"); : String c = "ab" + "cd"; : String tmp = "ab"; : String d = tmp + "cd"; : is a==b==c==d? : this is a very typical interview question. : Also make sure you know the concept of String Literal, as well as what : String.intern() does.