Exam Permalink:
https://www.jobilize.com/java-certification-questions
Question Permalink:
https://www.jobilize.com/inserting-into-a-treeset-in-java
Question 176 / 297:  The following code will throw a runtime exception, which line causes the exception?
import java.util.HashSet;

import java.util.Set;

import java.util.TreeSet;

public class Test{

public static void main(String[] args) {

Set s = new HashSet();

s.add("A"); // Line 1

s.add(new Foo()); // Line 2

Set t = new TreeSet();

t.add("A"); // Line 3

t.add(new Foo()); // Line 4

}

}

class Foo {}

A  Line 1
B  Line 2
C  Line 3
D  Line 4
<< First < Previous Next > Last >>
Explanation:

The two collections are non-generic, so anything is allowed to be added to these two collections.

But since TreeSet is a sorted collection, which means, what inserted in it should be Comparable, line 4 will cause a runtime exception because Foo is not Comparable.

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

Oracle Certified Professional Java Programmer

Author:

Access: Public Instant Grading

Ask
Nicole Bartels
Start Quiz
Yacoub Jayoghli
Start Quiz
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>