While I was trying to solve exercise from generics tutorial Q&A My answers were slightly different
My Answers
public static <T extends Comparable<? super T>>
T max(List<? extends T> list, int begin, int end) //Option1
public static <T extends Comparable<T>>
T max(List<? extends T> list, int begin, int end) //Option2
from quoted answer below
So My question is
Option1 :Would it make any difference if
T extends Object & Comparable<? super T>is replaced withT extends Comparable<? super T>. Isn'textends Objectimplicit ?Option2 :Would it make any difference if
Comparable<? super T>is replaced withComparable<T>? if so How ?Eclipse code completion creates local variable
List<? extends Comparable<? super Comparable<? super T>>> list;on Ctrl+1max(list, 1, 10);which is bit lengthy. How to Define a classes (hierarchy) that extendsComparable<? super T>, create list and add instances to the list and invoke below method ? Basically I want to know how to invokemax()after adding class instancesA or Binto a list whereclass B extends A
Write a generic method to find the maximal element in the range [begin, end) of a list.
Answer:
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;
}
}