The reason for the first comparison to fail is, that you do create two Objects by calling new
. Now, the ==
operator does compare two memory addresses, which yields the return you got because the two objects are not at the same memory cell.
The reason why it works with constant Strings is, that the java compiler, javac
, does optimize the code. By that optimisation similar string constants are being placed in one and the same memory cell. If you would have done the following, then the result would have been the same for your String
objects.
String s2 = new String("toto");
String s3 = new String("toto");
System.out.println(s2==s3); //yields false!!
Your way to go is .equals(other).
For that you'll have to implement the method equals in the class Mystring:
class MyString{
private String s;
public MyString (String s){
this.s = s;
}
public String getContent(){
return s;
}
@Override
public boolean equals(Object other){
if(other instanceof MyString){
MyString compareTo = (MyString) other;
return this.s.equals(compareTo.getContent());
}
return false;
}
}