Comparison of equal strings and sizes in Java
In C ++, the code for comparing two strings can be:
(String1 = string2)
However, in java, this code returns false even if the two strings are identical.
In Java, string1.equals (string2) must be used for judgment.
Supplement
If:
String s1 = "Hello ";
String s2 = "Hello ";
Then (s1 = s2) = true;
Because they point to the same object.
If:
String s1 = new String ("Hello ");
String s2 = new String ("Hello ");
Then (s1 = s2) = false
If the values of other variables are assigned to s1 and s2, false is returned even if the content is the same because it does not point to the same object. Therefore, we recommend that you use equals () Because equals compares the actual content.
For example:
String string1 = new String ("aaa ");
String string2 = new String ("aaa ");
Of course, these two strings should be equal.
If the expression string1 = string2 is used, the value of this expression is false.
If the expression string1.equals (string2) is used, the value of this expression is true.
Therefore, string1.equals (string2) should be used. In the if statement
If (string1.equals (string2) = true) // the string is equal ,......
String1 = string2, which has the same value and memory address and is completely equal
String1.equals (string2) is true, but the value is equal.
Use str1.compareTo (String str2) to compare the String size)
Compares two strings in alphabetical order. This comparison is based on the Unicode values of each character in the string. The character sequence represented by this String object is compared with the character sequence represented by the parameter String in alphabetical order. If the String object is placed before the parameter String in alphabetical order, the comparison result is a negative integer. If the String object is placed after the parameter String in alphabetical order, the comparison result is a positive integer. If the two strings are equal, the result is 0. compareTo returns 0 only when the equals (Object) method returns true.
This is the definition of dictionary sorting. If the two strings are different, they either have different characters at an index (the index is a valid index for both), or have different lengths, or both. If they have different characters at one or more index locations, assume k is the minimum value of these indexes; the character string with a smaller value on the position k (determined by the <operator), whose dictionary order is prior to other strings. In this case, compareTo returns the difference between the two strings at position k and the two char values, that is, the value:
This. charAt (k)-anotherString. charAt (k)
If there are no different character index locations, the dictionary order of the shorter string is prior to that of the longer string. In this case, compareTo returns the difference in the length of the two strings, that is, the value:
This. length ()-anotherString. length ()