This is the question from Oracle docs:
Write a generic method to find the maximal element in the range [begin, end) of a list.
I had my implementation like this:
public static <T extends Comparable> T maximalElement (List<T> list, int from, int to) {
T max = list.get(from);
for (int i = from + 1; i < to; i++) {
T elem1 = list.get(i);
if (elem1.compareTo(max) > 0) {
max = elem1;
}
}
return max;
}
When I viewed the answer, it was something like this:
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; }
So, I got the results running like this:
List<Integer> c = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println(Test.maximalElement(c, 3, 8));
System.out.println(Test.max(c, 3, 8));
Results are same, so I am quite excited that my version of generics is more simpler than one implemented in the answer. So, I want to check if my implemented version is really simpler and okay or am I not seeing something? Because oracle developers are not dumb enough to complex things out for nothing.
So, can you experts please help me understanding the difference or scenarios where my implemented version fails?