Source code (1): The toString () method in java, javatostring

Source: Internet
Author: User

Source code (1): The toString () method in java, javatostring

Preface:

The toString () method is believed to have been used by everyone. It is generally used to return data of objects in the form of strings.

  

A collection in the form of ArrayList <Integer> datas needs to be processed in a recent project.

Processing requires that the set data be converted into a string in the format of: child set 1 Data + "#" + child set 2 Data + "#" +... + child set n data.

For example, the set data: [[, 3], [, 5] must be converted to a string in the form of "[, 3] # [, 5 ]"

  

The first processing is as follows:

ArrayList <Object> a = new ArrayList <> (); // create a data set [[1, 2], [2, 3] the string [1, 2] # [2, 3] for (int I = 0; I <2; I ++) must be generated) {ArrayList <Object> c = new ArrayList <> (); c. add (I + 1); c. add (I + 2);. add (c); // print the string data Log of a single sub-set. I ("myinfo", c. toString ();} StringBuilder builder = new StringBuilder (); builder. append (. get (0 ). toString () + "#" +. get (1 ). toString (); // print the string form data Log of the set. I ("myinfo", builder. toString ());

  

Then, view the Log processed by the processing:

05-12 10:29:18.485 9565-9565/com.xxx.aaa I/myinfo: [1, 2]05-12 10:29:18.485 9565-9565/com.xxx.aaa I/myinfo: [2, 3]05-12 10:29:18.495 9565-9565/com.xxx.aaa I/myinfo: [1, 2]#[2, 3]

We will find that we want a string in the form of [1, 2] # [2, 3], but the result is [1, 2] # [2, 3]. After the second value starts, A space is added to the front.

  

Next, let's look at the source code of the. toString () method under the Set:

Translate the official explanation:

1. returns the string representation of the Collection class (the parent class of Set and List ).

2. The representation is in a specified format, which is included by the square brackets "[]".

3. The child element is separated by commas (,) and spaces (this is the focus)

    /**     * Returns the string representation of this {@code Collection}. The presentation     * has a specific format. It is enclosed by square brackets ("[]"). Elements     * are separated by ', ' (comma and space).     *     * @return the string representation of this {@code Collection}.     */    @Override    public String toString() {        if (isEmpty()) {            return "[]";        }        StringBuilder buffer = new StringBuilder(size() * 16);        buffer.append('[');        Iterator<?> it = iterator();        while (it.hasNext()) {            Object next = it.next();            if (next != this) {                buffer.append(next);            } else {                buffer.append("(this Collection)");            }            if (it.hasNext()) {                buffer.append(", ");            }        }        buffer.append(']');        return buffer.toString();    }

   

Analyze the source code of the. toString () method under this Collection, which is divided into several parts:

1. Check whether the set is empty (empty), that is, whether there is any data in the set. If it is null (no data), the string "[]" is returned directly.

2. If the set is not null, data exists.

① Iteration takes the next child element (Object next = it. next (). If the child element is the set itself, add "(this Collection)" to the buffer Object of the StringBuffer class

② If the child element is not a set, add it to the buffer object.

③ If there is a child element under this child element, add "," to the buffer object to separate two adjacent child elements.

3. returns the StringBuffer. toString () string.

  

Therefore, if [1, 2] # [2, 3] is returned in the correct official format, in fact, if the source code cannot be changed, use it after the obtained string. replaceAll ("", ""); remove all spaces in the string

  

Note: There is a piece of code in the source code:

            if (next != this) {                buffer.append(next);            } else {                buffer.append("(this Collection)");            }         

Some of you may not understand it here. Here is an example of the above. We will add code c in the child set. add (c); add the set itself to the set to see the printed result

ArrayList <Object> a = new ArrayList <> (); for (int I = 0; I <2; I ++) {ArrayList <Object> c = new ArrayList <> (); c. add (I + 1); c. add (I + 2); c. add (c); // print the string data Log of a single sub-set. I ("myinfo", c. toString ());}

Check whether the red part in the log result is understood. If the sub-element in the set is the set itself, add "(this Collection)" to the returned set.

05-12 10:58:00. 615 8424-8424/com. maiji. magkarepatient I/myinfo: [1, 2, (this Collection)]
05-12 10:58:00. 615 8424-8424/com. maiji. magkarepatient I/myinfo: [2, 3, (this Collection)]

  

So far, the above problem has been solved. Next we will look at the. toString () source code under other classes.

  

Bytes ---------------------------------------------------------------------------------------------------------------

 

I. Object

 /**     * Returns a string containing a concise, human-readable description of this     * object. Subclasses are encouraged to override this method and provide an     * implementation that takes into account the object's type and data. The     * default implementation is equivalent to the following expression:     * <pre>     *   getClass().getName() + '@' + Integer.toHexString(hashCode())</pre>     * <p>See <a href="{@docRoot}reference/java/lang/Object.html#writing_toString">Writing a useful     * {@code toString} method</a>     * if you intend implementing your own {@code toString} method.     *     * @return a printable representation of this object.     */    public String toString() {        return getClass().getName() + '@' + Integer.toHexString(hashCode());    }

Translate the official explanation:

1. Return a concise and readable string for this Object

2. Subclass of the Object class is encouraged to override this method to provide an implementation for describing the Object type and Data

3. The default execution format is the same as the following example.

getClass().getName() + '@' + Integer.toHexString(hashCode())</pre>

To sum up, when the. toString () method is not overwritten in one of your classes, the. toString () method of the root class Object will be executed.

Return format: Class Name of the Object + @ + hexadecimal Hash Value

GetClass (). getName () returns the class name hashCode () of the object's class and returns the hash value Integer of the object. toHexString (hashCode () represents the object's hash value in hexadecimal notation

Example:

Object d = new Object();Log.i("myinfo",d.toString());05-12 11:23:00.758 17406-17406/com.maiji.magkarepatient I/myinfo: java.lang.Object@e23e786

 

Ii. String, StringBuilder, StringBuffer

The three are the expressions of strings, but they are different.

①. String. toString (), directly return itself

    /**     * Returns this string.     */    @Override    public String toString() {        return this;    }

② StringBuilder

Official explanation: return the content of this builder object in the form of a string

/**     * Returns the contents of this builder.     *     * @return the string representation of the data in this builder.     */    @Override    public String toString() {        /* Note: This method is required to workaround a compiler bug         * in the RI javac (at least in 1.5.0_06) that will generate a         * reference to the non-public AbstractStringBuilder if we don't         * override it here.         */        return super.toString();    }

Tracing to super. toString () Implementation

 /**     * Returns the current String representation.     *     * @return a String containing the characters in this instance.     */    @Override    public String toString() {        if (count == 0) {            return "";        }        return StringFactory.newStringFromChars(0, count, value);    }

  

③ StringBuffer

@Override    public synchronized String toString() {        return super.toString();    }

  

Tracing to super. toString ()

 /**     * Returns the current String representation.     *     * @return a String containing the characters in this instance.     */    @Override    public String toString() {        if (count == 0) {            return "";        }        return StringFactory.newStringFromChars(0, count, value);    }

    

In summary, we found that StringBuffer and StringBuilder finally call the toString () method in the parent "AbstractStringBuilder ".

However, their own toString () is different, so we can sum up

1. StringBuilder: thread-safe

StringBuffer: thread-safe

2. The processing speed of StringBuilder is much faster than that of StringBudiler.

3. A large number of data operations on a single thread. Use StringBuilder because StringBuilder is fast and security is not considered because of single thread.

Multi-threaded massive data operations, using StringBuffer, because StringBuffer is safe

 

3. Map

First look at the source code:

The returned format is {key1 = value1, key2 = value2}

Note 1: when there is no data in the Map set, {} is returned {}

2. Use "," to separate each two data items, which is consistent with the Collection items. a comma and a space are used.

3. When the key value is set, add (this Map)

public String toString() {        Iterator<Entry<K,V>> i = entrySet().iterator();        if (! i.hasNext())            return "{}";        StringBuilder sb = new StringBuilder();        sb.append('{');        for (;;) {            Entry<K,V> e = i.next();            K key = e.getKey();            V value = e.getValue();            sb.append(key   == this ? "(this Map)" : key);            sb.append('=');            sb.append(value == this ? "(this Map)" : value);            if (! i.hasNext())                return sb.append('}').toString();            sb.append(',').append(' ');        }    }

Example:

Map <String, String> map = new HashMap <> (); map. put ("keyA", "valueA"); map. put ("keyB", "valueB"); map. put ("keyC", "valueC"); Log. I ("myinfo", map. toString ());

Print result:

05-12 11:41:30. 898 4490-4490/com. maiji. magkarepatient I/myinfo: {keyA = valueA, keyB = valueB, keyC = valueC}

  

 

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.