This article mainly introduces the difference between Java and JavaScript in judging whether two strings are equal. It is very good and has reference value. Friends in need can refer to it
Javascript is a commonly used scripting language, which also determines that it is not very standardized compared to other programming languages. To determine whether two strings are equal in Javascript, use == directly. This It is the same as the String class in C++. The equal sign in Java is used to determine whether the references of two strings are the same. To determine the entity, you need to use the equals() method or the
or compareTo() method. It needs to be emphasized here. is the parameter type of the equals() method. Its parameter type is definitely not the String class, but the Object class. We have seen more than once that some domestic tutorials write the String class (o(╯□╰)o )
You can take a look at 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 = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; 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. By the way, let’s talk about this code. First, judge whether the two references are the same. If the references are the same, If the entities are naturally the same, then it involves class conversion:
We assign the object
created by the subclass to the parent class, which we call an up-transformation object. On this basis, you can also convert parent class objects into subclass objects. Simply put, there are certain conditions for conversion between classes, and instanceof needs to be used to judge.
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 the compareTo() method of the String class in Java:
public int compareTo(String anotherString) { int len1 = value.length; int len2 = anotherString.value.length; int lim = Math.min(len1, len2); char v1[] = value; char v2[] = anotherString.value; 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 Most classes have implemented this interface (ps: one comes from inheritance and the other comes from interface, which is why the parameter types of the two are inconsistent).
The above is the detailed content of Detailed introduction to the difference between judging whether two strings are equal in Java and JavaScript. For more information, please follow other related articles on the PHP Chinese website!