[Java beginner] println method without collection type specification

Question

I recently studied the collection and had some doubts, so I will review it in the article.

collection

If you do not specify a type argument when using List, it will be processed as ** Object type ** when it is stored.

Mystery processing that I could not understand

I put a ** String type ** variable in the List, but since I haven't specified the type of List, it becomes ** Object type **, and ** the character string ** of that object is displayed by println ...?

println processing

Call the ** valueOf ** method of the object put in the argument of ~~ println to display the string. ~~ <Fixed 2019/05/24> The argument of println () is given to the argument of the static method valueOf () of String class and processing is performed.

Difference between toString and valueOf

The toString method returns a string of instances. The valueOf method calls the toString method of the object if the object passed as an argument is not null.

After all toString

valueOf also eventually returns the string for that object.

User.java


public class User{
    private String name;
    public User(String name){
         this.name = name;
    }
    public String toString(){
         return name;
    }
}

Main.java


public class Main{
   public static void main(String[] args){
      ArrayList list = new ArrayList();
      list.add(new User("sample"));
      System.out.println(list.get(0)); //sample
   }
}

result

I got a better understanding of type safety and Override.

reference

Recommended Posts

[Java beginner] println method without collection type specification
Java test code method collection
Java beginner design pattern (Factory Method pattern)
[Java] Express Enum type without using Enum (enumeration) type
Java method
java (method)
☾ Java / Collection
[Beginner] Java method / class / external library [Note 23]
java beginner 3
java beginner
[Java] method
[Java] method
[Java SE 11 Silver] Arrays class method summary [Java beginner]
Java type conversion
[JAVA] Stream type
[Java] Enumeration type
Java Optional type
Java8 method reference
Java Reintroduction-Java Collection
[Java] forEach method
Java Beginner Exercises
Java double type
java8 method reference
[Java] Random method
[Java] split method
Java specification memo
[Java] Collection framework
Java Exercise "Beginner"
[Beginner] Java class field method / encapsulation (getter setter) [Note 25]