JavaScript is a commonly used scripting language, which also determines that it is not very standardized compared to other programming languages. In JavaScript, determine whether two strings are equal.
Use == directly, which is the same as the String class in C++. The equal sign in Java is to determine whether the references of two strings are the same. To determine the entity, use the equals() method, or
The compareTo() method needs to be emphasized here is the parameter type of the equals() method. The parameter type is definitely not the String class, but the Object class. We have seen it more than once.
Some tutorials in China write String class (o(╯□╰)o)
You can check out the source code of JDK:
public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String) anObject; int n = ; if (n == ) { char v1[] = value; char v2[] = ; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }
We can see that the parameter type is Object class, and we will also talk about this code. First, we will determine whether the references between the two are the same. If the references are the same, the entities will naturally be the same. Next, we will involve the conversion of the class:
We assign objects created by subclasses to the parent class, which we call the upper transformation object. On this basis, you can also convert the parent class object into a child class object. Simply put, the conversion between classes has certain conditions and needs to be judged by instanceof.
The equals() method in each class comes from the Object class, so it is not difficult to understand that the parameter type of the equals() method is the Object class. It is worth mentioning that compareTo() of String class in Java
method:
public int compareTo(String anotherString) { int len1 = ; int len2 = ; int lim = (len1, len2); char v1[] = value; char v2[] = ; int k = 0; while (k < lim) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) { return c1 - c2; } k++; } return len1 - len2; }
The parameter in compareTo() is the String class because the String class implements the Comparable interface. Basically, most classes implement this interface (ps: one comes from inheritance and the other comes from interface. This is why the parameter types of the two are inconsistent).
The above is the difference between judging whether two strings are equal in Java and JavaScript introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!