Exam Permalink:
https://www.jobilize.com/java-certification-questions
Question Permalink:
https://www.jobilize.com/inserting-into-a-nongeneric-collection-in-java
Question 177 / 297:  What is the expected output of compiling and running the following code?
import java.util.ArrayList;

import java.util.List;

public class Test{

public static void main(String[] args) {

List list = new ArrayList();

list.add("Hello");

Foo f = new Foo();

list.add(f);

f = list.get(1);

System.out.print(list.get(0) + "-" + f);

}

}

class Foo {

public String toString() {

return "Foo";

}

}

A  Hello-Foo
B  compilation error
C  exception at run time
<< First < Previous Next > Last >>
Explanation:

f = list.get(1) causes a compilation error, it must be casted to (Foo).

list is a non-generic collection, which means any type of object is allowed to be inserted in it. But because it is a non-generic collection, it means when fetching its elements, the return type of the fetched element will be Object not the actual type of the element. Therefore, we need to cast the element to its actual type.

Exam Home Page
https://www.jobilize.com/java-certification-questions

Oracle Certified Professional Java Programmer

Author:

Access: Public Instant Grading

Ask
Savannah Parrish
Start Exam
Darlene Paliswat
Start Test
Copy and paste the following HTML code into your website or blog.
<iframe src="https://www.jobilize.com/embed/java-certification-questions" width="600" height="600" frameborder="0" marginwidth="0" marginheight="0" scrolling="yes" style="border:1px solid #CCC; border-width:1px 1px 0; margin-bottom:5px" allowfullscreen webkitallowfullscreen mozallowfullscreen> </iframe>