Recently, I was blessed with the opportunity to use Java because of my work. I updated my ancient Java (1.3) knowledge.
This function determines the processing of the type to be used at the time of implementation.
This alone is refreshing, so I would like to explain it with an example.
List list = new ArrayList();
//Store value in list
// String ->Since it is a conversion to Object, it can be stored implicitly.
list.add("1");
list.add("2");
list.add("3");
for (Iterator it = list.iterator(); it.hasNext(); ) {
//Get and display the value of list
//Object at the time of acquisition->String needs an explicit cast
String str = (String) it.next();
System.out.println(str);
}
//Prepare ArrayList that uses String type
List<String> list = new ArrayList<String>();
// List<String> list = new ArrayList<>(); //Since the type is fixed when the variable is declared, when creating an instance<>Can be omitted
//Store value in list
//String can be stored as it is
list.add("1");
list.add("2");
list.add("3");
for (Iterator<String> it = list.iterator(); it.hasNext(); ) {
//Get and display the value of list
//No need to cast because it can be obtained as a String
String str = it.next();
System.out.println(str);
}
In Java1.3, when using collections I had to store it as an Object type. Of course, when extracting it, it is also an Object type, so I had to cast it according to the type used.
The songwriter is to cast when this is taken out If you store the wrong type, you will get a ClassCastException. Of course, it's an Exception, so you won't notice the mistake until you run it.
On the other hand, if you use Generics, you can determine the type at the time of implementation.
Wrong type to store = Compile error occurred
It is also a function that helps reduce easy mistakes.
Recommended Posts