Check Java toString () implementation

A toString method that returns a string representation of an object in Java. I usually use it properly, but I checked the implementation of the contents

Introduction (Usage example)

Hoge.java


public class Hoge{
  @Override 
  public String toString(){
    return "This class is the Hoge class.";
  }
}

Test1.java


public class Test1{
  public static void main(String[] args){
    Object hoge = new Hoge();
    System.out.println(hoge);
  }
}

If you override the toString method appropriately like this, It's a convenient function that displays good things just by putting it in the argument of print. (The operation when it can be interpreted as a character string is also handled well.)

Confirmation of implementation

This time, I will confirm this implementation.

First, from Document description.

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. This result should be concise and informative for human readability. We recommend that you override this method in all subclasses. The toString method of class Object returns a string consisting of the name of the original class in which the object is an instance, the atmark character "@", and an unsigned hexadecimal representation of the object's hash code. That is, this method returns a string equal to the following values:

getClass().getName() + '@' + Integer.toHexString(hashCode())

The toString method is implemented in the Object class and by default Shows the class name and hash code.

The Object class is a superclass of all Java classes, so All classes have a toString method.

Usage of toString

The toString method is usually handled like this I guessed.

  1. Object-to-string conversion (explicit)
  2. String concatenation operator (implicit)

Let's check if this hypothesis is correct.

Object-to-string conversion

For example, the implementation of System.out.println is

Therefore, when Object is used as an argument Checking the implementation of System.out.println,

PrintStream.java



    public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
            print(s);
            newLine();
        }
    }

In this way, we call Object # valueOf ().

String.java


    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

If you check the implementation of the String class, If the argument object is not null, toString is called. (Avoid NullPointer)

String concatenation operator

Since the concatenation by the string concatenation operator is based on the "Java Language Specification", Processing differs depending on the version. Since it is complicated, I will omit the details, but by the string concatenation operator + The code seems to be treated as StringBuilder.append () behind the scenes.

The image seems to look like this.

Test2.java


public class Test2{
  public static void main(String[] args){
    "time: " + new Date();
    // new StringBuilder().append("time: ").append(new Date());
  }
}

Therefore, let's check the implementation of StringBuilder.

StringBuilder.java


    @Override
    public StringBuilder append(Object obj) {
        return append(String.valueOf(obj));
    }

Ah...


# By the way

The array does not show the contents of the list, but the array list does.
Sometimes it's hard to make a mistake.

ArrayList superclass, AbstractCollection
I overridden toString.


#### **`AbstractCollection.java`**
```java

  public String toString() {
       Iterator<E> it = iterator();
       if (! it.hasNext())
           return "[]";

       StringBuilder sb = new StringBuilder();
       sb.append('[');
       for (;;) {
           E e = it.next();
           sb.append(e == this ? "(this Collection)" : e);
           if (! it.hasNext())
               return sb.append(']').toString();
           sb.append(',').append(' ');
       }
   }
```

Apparently, [the array is defined by the language specification](https://docs.oracle.com/javase/specs/jls/se10/html/jls-10.html#jls-10.7)
Looking at this, it feels like that because the toString method is not overridden.

```java
class A<T> implements Cloneable, java.io.Serializable {
   public final int length = X;
   public T[] clone() {
       try {
           return (T[])super.clone();
       } catch (CloneNotSupportedException e) {
           throw new InternalError(e.getMessage());
       }
   }
}
```

The length of the beginner's cry, was it final in your public ...


# At the end

toString Convenient.


Recommended Posts

Check Java toString () implementation
Java version check
Java check process
Interpreter implementation in Java
Boyer-Moore implementation in Java
Heapsort implementation (in java)
[Implementation] Java Process class notes
Check Java9 Interface private methods
[Java] Implementation of Faistel Network
[Java] Timer processing implementation method
Check https connection in Java
Implementation of gzip in java
Implementation of tri-tree in Java
[Java 8] Duplicate deletion (& duplicate check) with Stream
Java 15 implementation and VS Code preferences
[Java] Element existence check with Stream
Java
Check Java parameters in Kubernetes pods
BloomFilter description and implementation sample (JAVA)
[Java] Date period duplication check sample
Java
Implementation of like function in Java
How to check Java installed on Mac
Implementation of clone method for Java Record
Implementation of DBlayer in Java (RDB, MySQL)
Check the contents of the Java certificate store
Memo: [Java] Check the contents of the directory
[Java] How to use the toString () method
Java implementation to create and solve mazes
Try using JobScheduler's REST-API --Java RestClient implementation--
Java automated test implementation with JUnit 5 + Gradle
[Java] New Yahoo! Product Search API Implementation
[Java] Check the number of occurrences of characters
Check heap usage with Java Flight Recorder
[Java] Is it unnecessary to check "identity" in the implementation of the equals () method?