Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How do I rewrite equals in Strings?


May 28, 2021 Article blog



The equals method is the Object class definition method, and Object is the parent of all classes, which also includes string, String overrides the equals method, and let's see how to override it.

 How do I rewrite equals in Strings?1

The first step is to determine whether the quotation marks of the two strings that need to be compared are equal, and if the quotation marks return true directly if they are equal, do not equally continue the following judgment

The second part then determines whether the object has an instance of String, returns false if not, and, yes, if the length of the two strings is equal, there is no need to compare the difference. False is returned if one is not equal if the characters of the two strings are equal.

The flowchart is as follows:

 How do I rewrite equals in Strings?2

Questions:

if (this == anObject) {
  return true;
}

How does the judgment statement return true? I s the string comparing heap space? The String.intern() method means that concepts differ from JDK versions

After JDK1.7, the intern method determines whether the running constant pool has a specified string, and if not, adds the string as a constant pool, returning its object.

private void StringOverrideEquals(){

  String s1 = "aaa";
  String s2 = "aa" + new String("a");
  String s3 = new String("aaa");

  System.out.println(s1.intern().equals(s1));
  System.out.println(s1.intern().equals(s2));
  System.out.println(s3.intern().equals(s1));

}

That's how equals in String is rewritten by the little editor. the whole content