Exam Permalink:
https://www.jobilize.com/java-certification-questions
Question Permalink:
https://www.jobilize.com/how-to-implement-comparable-in-java
Question 199 / 297:  What is the result of compiling and running the following code?
import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

public class Test{

public static void main(String[] args) {

List<Human> humans = new ArrayList<Human>();

humans.add(new Human(13));

humans.add(new Human(33));

humans.add(new Human(21));

humans.add(new Human(21));

Collections.sort(humans);

System.out.print(humans.get(0).age);

System.out.print(humans.size());

}

}

class Human implements Comparable<Human> {

int age;

public Human(int age) {

this.age = age;

}

public int compareTo(Human h) {

return h.age.compareTo(this.age);

}

}

A  333
B  334
C  133
D  134
E  Compilation fails
<< First < Previous Next > Last >>
Explanation:

Pay attention to the type of age in class Human, it is the primitve type "int", and you cannot invoke method compareTo on a primitive type, this causes a compilation error.

If type of age is Integer, the output would be 334

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

Oracle Certified Professional Java Programmer

Author:

Access: Public Instant Grading

Ask
Anonymous User
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>