What is the difference between java String and android String ?, Stringandroid

Source: Internet
Author: User

What is the difference between java String and android String ?, Stringandroid
This is what Alibaba was asked during the telephone interview today. I did not think about it before (I always thought it was the same). So after the interview, I immediately opened the source code, the two String classes are compared. The following is my findings. First, I observed the packages imported by the two String classes and found some differences between the two:

This is the android version:

Import java. io. serializable; import java. io. unsupportedEncodingException; import java. nio. byteBuffer; import java. nio. charBuffer; import java. nio. charset. charset; import java. nio. charset. charsets; import java. util. arrays; import java. util. comparator; import java. util. formatter; import java. util. locale; import java. util. regex. pattern; import libcore. util. emptyArray; // This seems to be google's own api class library

This is the java version:

import java.io.ObjectStreamField;import java.io.UnsupportedEncodingException;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.Arrays;import java.util.Comparator;import java.util.Formatter;import java.util.Locale;import java.util.regex.Matcher;import java.util.regex.Pattern;import java.util.regex.PatternSyntaxException;

We can see that the android version has some classes in the nio package, and android visually optimizes the performance of the String class. Next, I found that the compareToIgnoreCase methods of the two classes are different: android version:
 public int compareToIgnoreCase(String string) {        int o1 = offset, o2 = string.offset, result;        int end = offset + (count < string.count ? count : string.count);        char c1, c2;        char[] target = string.value;        while (o1 < end) {            if ((c1 = value[o1++]) == (c2 = target[o2++])) {                continue;            }            c1 = foldCase(c1);            c2 = foldCase(c2);            if ((result = c1 - c2) != 0) {                return result;            }        }        return count - string.count;    }

Java version:

  public int compareToIgnoreCase(String str) {        return CASE_INSENSITIVE_ORDER.compare(this, str);    }

After a closer look, the logic is actually the same. android writes the logic to compareToIgnoreCase, while the compare method in CaseInsensitiveComparator calls compareToIgnoreCase, which is the opposite for java. Next, I found that many android methods have become local methods:
public native char charAt(int index); public native int compareTo(String string);public native boolean equals(Object object);private native int fastIndexOf(int c, int start);public native boolean isEmpty();public native int length();

These methods are not native in java:

public char charAt(int index) {        if ((index < 0) || (index >= value.length)) {            throw new StringIndexOutOfBoundsException(index);        }        return value[index];    }    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;    }   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;    }

It can be seen that android optimizes frequently-used APIs through local methods, which is more efficient than the java version. In addition, I also found that many android methods are annotated, such as @ FindBugsSuppressWarnings, @ SuppressWarnings, and so on. java version does not.
Restricted by the individual level, the analysis can only be done now ~





Differences between string and String in java

All are identifiers
String generally refers to the java. lang. String class, as a String
String is generally used as the name of a String type object.
String-> string
It is like:
Man-Xiao Wang
Relationship
Du tianwei [authoritative expert]

In Java, what is the difference between string and bufferstring?

The String class is used to indicate the strings that will not be changed after creation. It is immutable.
The StringBuffer class is used to represent variable strings and provides methods to modify underlying strings.
When concatenating characters, use the StringBuffer class instead of the String class, because the former is a hundred times faster than the latter.
Indeed, in many cases of the program, we will concatenate strings. A simple code example is as follows:
String str = "You are nice .";
Str + = "I love you so much .";
If the StringBuffer class is used, the Code is as follows:
StringBuffer str = new StringBuffer ("You are nice .");
Str. append ("I love you so much .");
On the surface, the String class uses only one plus sign (+) to concatenate strings, while the StringBuffer class calls an append () method. Is it more concise and simple to implement? Otherwise, let's take a look at what happened inside the program:
After compilation, the bytecode (bytecode) of the program shows the essence: When the String class object is directly spliced, JVM creates a temporary StringBuffer Class Object and calls its append () this is because the String class is unchangeable and the concatenation operation has to use the StringBuffer class (and -- JVM will set "You are nice. "and" I love you so much. "created as two new String objects ). Then, the temporary StringBuffer object is transformed into a String, which is expensive! We can see that in this simple splicing process, we have the program create four objects: two strings to be spliced, a temporary StringBuffer, and the String that finally transforms StringBuffer into -- it is not the original str, and the referenced name is not changed, but it points to the New String object.
If you directly use the StringBuffer class, the program will generate only two objects: the initial StringBuffer and the String ("I love you so much. "), you do not need to create a temporary StringBuffer class object and then convert it back to the String object.
We can imagine how much additional system overhead will be incurred when we use the String class for direct operations when our strings are to be concatenated by several segments cyclically, and how many useless temporary StringBuffer objects will be generated, and how many unnecessary forced type conversions are processed.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.