1

Oracle provides some java generics questions with answers. This is problem 8.

Write a generic method to find the maximal element in the range [begin, end) of a list.

solution

import java.util.*;

public final class Algorithm {
    public static <T extends Object & Comparable<? super T>>
        T max(List<? extends T> list, int begin, int end) {

        T maxElem = list.get(begin);

        for (++begin; begin < end; ++begin)
            if (maxElem.compareTo(list.get(begin)) < 0)
                maxElem = list.get(begin);
        return maxElem;
    }
}

In the method signature

public static <T extends Object & Comparable<? super T>> T max(List<? extends T> list, int begin, int end)

What is the point of stating that T must extend Object? Doesn't everything do that anyway? Is this redundant?

ThatDataGuy
  • 1,969
  • 2
  • 17
  • 43
  • Or https://stackoverflow.com/questions/32795995/java-generics-special-usage-t-extends-object-interface – Savior Apr 07 '20 at 18:06
  • Or https://stackoverflow.com/questions/30206340/what-is-the-difference-between-t-and-t-extends-object-in-java – Savior Apr 07 '20 at 18:08
  • From the accepted answer on 8055389 they link the oracle docs, which use something very close to your specific example. https://docs.oracle.com/javase/tutorial/extra/generics/convert.html – matt Apr 07 '20 at 18:32

0 Answers0