ProgrammingVery hardProduct-company placement · Java
Which line fails to compile?
Which line fails to compile?
class Fruit implements Comparable<Fruit> { public int compareTo(Fruit o) { return 0; } }
class Apple extends Fruit { }
// static methods of the main class:
static <T extends Comparable<T>> T max1(List<T> l) { return l.get(0); }
static <T extends Comparable<? super T>> T max2(List<T> l) { return l.get(0); }
// in main:
List<Apple> apples = List.of(new Apple());
max1(apples); // L1
max2(apples); // L2- A. L2 only
- B. Both
- C. L1 only
- D. Neither
Correct answer: C. L1 only
Apple is Comparable<Fruit>, not Comparable<Apple>, so T = Apple violates T extends Comparable<T>. The bound Comparable<? super T> accepts comparability inherited from a supertype; this is why Collections.max uses it.
More OOP with C++ and Java questions
- Which line fails to compile? java // Java 16 or later Object o = "hello"; if (o instanceof String s && s.length() > 3)…
- What is printed? java Set<Short> s = new HashSet<>(); for (short i = 0; i < 5; i++) { s.add(i); s.remove(i - 1); }…
- What is printed? java Map<Long, String> m = new HashMap<>(); m.put(1L, "one"); System.out.print(m.get(1) + " " + m.get(1L) + " " +…
- What is printed? java List<Character> l = new ArrayList<>(List.of('a', 'b')); System.out.print(l.contains('a') + " " + l.contains(97) + "…
- What is printed? java Function<Integer, Integer> f = x -> x + 1; Function<Integer, Integer> g = x -> x 2…
- What is printed? java List<String> l = new ArrayList<>(List.of("ccc", "ee", "a", "bb", "d"))…