Page 1 of 1

About Question enthuware.ocpjp.i.v11.2.3058 :

Posted: Mon Dec 09, 2019 12:07 pm
by demetrio
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?

Re: About Question enthuware.ocpjp.i.v11.2.3058 :

Posted: Mon Dec 09, 2019 10:10 pm
by admin
>Does it mean that I should always declare either with a known type (eg. new ArrayList<Student>()) or ignoring generic (eg. new ArrayList())?
No, the declaration depends on what you want to achieve. Although, I agree that uses for new ArrayList<>(); will be hard to find.

There is nothing wrong with var allStudents = new ArrayList<>(); from the compiler's perspective. You can still get elements from the list like this: Object obj = allStudents.get(0); So, the compiler has no reason to reject it.

Re: About Question enthuware.ocpjp.i.v11.2.3058 :

Posted: Mon Jun 22, 2020 11:29 pm
by dimitrilc
I think the explanation for answer //6 contradicts with why //5 works?

The explanation said, "the type of the objects in the list is not known", but apparently the type of objects in allStudents is Object so //5 can work.

If the type of elements in allStudents is truly unknown, then the usage of LVTI at //5 wouldn't be possible, right?

So is it more correct to say that,
//6 does not work because the type of elements inside allStudents are treated as Object type by the compiler?

Using an explicit cast allows //6 to compile as well.

Code: Select all

Student s2 = (Student) allStudents.get(0);
Can we also conclude that, when the empty diamond operator is used to declare an arrayList, the compiler treats all elements as Objects?

Re: About Question enthuware.ocpjp.i.v11.2.3058 :

Posted: Tue Jun 23, 2020 12:30 am
by admin
Yes, you are right. This explanation was actually updated only yesterday in the latest update to the question bank. Hasn't propagated to people yet :)

ArrayList<> means that it is an ArrayList of Object instances. You can add Object instances (or its subclass instances because all objects are Objects) but take out only Object instances.