I recently studied the collection and had some doubts, so I will review it in the article.
If you do not specify a type argument when using List, it will be processed as ** Object type ** when it is stored.
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 ...?
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.
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.
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
}
}
I got a better understanding of type safety and Override.
Recommended Posts