LearnFrenzy
Sign in Take a free test

Generics · Find the Error · Question 7

Error: calling compareTo on an unbounded T Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
public class Main {
    static <T> T larger(T a, T b) {
        return a.compareTo(b) >= 0 ? a : b;
    }

    public static void main(String[] args) {
        System.out.println(larger(3, 9));
    }
}
  • A larger must not be static
  • B An unbounded T is only known to be an Object, which has no compareTo; declare <T extends Comparable<T>> Correct
  • C Integers cannot be compared
  • D The ternary operator is not allowed
Correct Answer: Option B

Bounds unlock methods; without one, only Object's methods are available.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links