Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come generic type parameter says "extends" Comparable not "implements"? [duplicate]

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 an interface so why is it 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 related to this topic.

http://www.tutorialspoint.com/java/java_generics.htm

like image 901
Meow Avatar asked Jul 24 '10 20:07

Meow


People also ask

What does extends comparable mean in Java?

Implementing the Extends Comparable<T> Interface in Java This method compares the object with the specified object for the order. It returns a negative integer if the object is less than specified. It will return zero if the object and the specified object are equal.

Can a generic class have multiple generic parameters?

A Generic class can have muliple type parameters.

What does comparable E mean?

This means that the type parameter must support comparison with other instances of its own type, via the Comparable interface.

Can a generic class have multiple generic parameters Java?

Java Generics TutorialA generic class can have multiple type parameters. In this article, we will learn how to create a generic class and interface with multiple type parameters examples.


1 Answers

This is just the convention chosen for generics. When using bounded type parameters you use extends (even though it might mean implements in some cases) or super.

You can even do something like <E extends Comparable<E> & Cloneable> to define that the object that would replace the type parameter should implement both those interfaces.

like image 63
Andrei Fierbinteanu Avatar answered Oct 31 '22 18:10

Andrei Fierbinteanu