About Question enthuware.ocpjp.i.v11.2.3058 :
Posted: Mon Dec 09, 2019 12:07 pm
public class TestClass {
var students = new ArrayList<Student>(); //1
public static void main(String[] args) {
var student = new Student(); //2
var allStudents = new ArrayList<>(); //3
allStudents.add(student); //4
Student s2 = allStudents.get(0); //6
}
}
The reason for failling at line 6 is: "Observe that new ArrayList<>() means the type of the objects in the list is not known. So, you cannot assign an object retrieved from this list to a Student variable. Had it been new ArrayList<Student>(), the assignment would have been valid." Does it mean that I should always declare either with a known type (eg. new ArrayList<Student>()) or ignoring generic (eg. new ArrayList())? If so, shouldn't compiler reject "new ArrayList<>();" since I can“t use allStudents anyway?
var students = new ArrayList<Student>(); //1
public static void main(String[] args) {
var student = new Student(); //2
var allStudents = new ArrayList<>(); //3
allStudents.add(student); //4
Student s2 = allStudents.get(0); //6
}
}
The reason for failling at line 6 is: "Observe that new ArrayList<>() means the type of the objects in the list is not known. So, you cannot assign an object retrieved from this list to a Student variable. Had it been new ArrayList<Student>(), the assignment would have been valid." Does it mean that I should always declare either with a known type (eg. new ArrayList<Student>()) or ignoring generic (eg. new ArrayList())? If so, shouldn't compiler reject "new ArrayList<>();" since I can“t use allStudents anyway?