Difference between Java and JavaScript in judging whether two strings are equal or not

  • 2021-08-03 08:47:48
  • OfStack

JavaScript is a commonly used scripting language, which also determines that it is not very standard compared with other programming languages. Judge whether two strings are equal in JavaScript

Directly use = =, which is like String class 1 in C + +. In Java, the equal sign is to judge whether the reference of two strings is like 1, and to judge the entity, you need to use equals () method, or

For compareTo () method, what needs to be emphasized here is the parameter type of equals () method. Its parameter type is definitely not String class, but Object class. Let's look at it more than once

Some tutorials written in China are String class (o (-) o)

You can 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 references are the same. If the references are the same, the entities are naturally the same. Next, it involves the conversion of classes:

We assign the object created by the subclass to the parent class, which we call the upper transformation object. On this basis, you can also convert parent class objects into subclass objects. Simply put, the conversion between classes has 1 definite condition, and needs to be judged by instanceof.

The equals () method in each class is derived 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

Methods:


 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 String class, because String class implements Comparable interface. Basically, most classes implement this interface (ps: 1 comes from inheritance and 1 comes from interface, which is the reason why the parameter types of the two are not 1).


Related articles: