I tried to write generic function that remove the duplicate elements from array.
public static <E extends Comparable<E>> ArrayList<E> removeDuplicate(E[] arr) {
//do quicksort
Arrays.sort(arr);
ArrayList<E> list = new ArrayList<E>();
int i;
for(i=0; i<arr.length-1; i++) {
if(arr[i].compareTo(arr[i+1]) != 0) { //if not duplicate, add to the list
list.add(arr[i]);
}
}
list.add(arr[i]); //add last element
return list;
}
As you can see you can't pass primitive type like int[] array since I am comparing elements by compareTo() method that defined in Comparable interface.
I noticed the first line (method declaration):
public static <E extends Comparable<E>> ArrayList<E> removeDuplicate(E[] arr) {
How come it says "extends Comparable" ?
Comparable is interface so why it is not "implement Comparable"? This is first time I wrote generic function so I'm bit confused about such detail. (any wondering would prevent me from understanding..)
EDIT: Found this article that mentions about the topic.