This problem is driving me nuts! I have declared a static string in a constants class as follows:
public static final String REGISTRATION_USERNAME_TAKEN = "Username is already in use. Please choose a different name.";
After a call to a restful web service to register a user, the response (during debugging) is caught and compa开发者_运维问答red to the constant. The response also appears in double double quotes (not sure why) and the result.equals() fails, even though both the result and the constant look exactly the same. Below is a screen capture during debugging in Eclipse which shows the double double quotes. The character count of 61 includes one set of double quotes.
Has anyone seen this before in Eclipse? Also, why does .equals() fail when both strings have the same values (by that I mean both strings contain the same characters in the same sequence)?
Regarding the .equals() method failing when comparing a String to an enum constant, actually that's the default behaviour in case you didn't override the toString() method in the enum class.
eg :
public MyEnum
{
LIL, LOL
}
//try inside main method
String result = "LOL";
if(result.equals(MyEnum.LOL))
System.out.println("true");
else
System.out.println("false"); //will print false
so if you want to compare a String to the exact String value that an enumeration may have, you can either add a private field to the enumeration that would hold their corresponding String value that you would define inside a constructor and return by overriding toString() inside the enumeration, or you can force the use of toString() simply by doing this :
if(result.equals((MyEnum.LOL).toString())
//same code as before would print true
精彩评论