简体   繁体   中英

Generics - Collections sort method

When using Collections.sort(List<T> list) , with List<Employee> , where Employee is a class which does not extend Comparable interface.

Then I see following compilation error

The method sort(List<T>) in the type Collections is not applicable for the arguments ( List<Employee> ).

I dont understand why T should implement Comparable , it's not specified anywhere in the method arguments of sort method.

Update : Please stop downvoting. I always thought only method parameter decides what to be passed as argument, but I see <T extends Comparable<? super T>> <T extends Comparable<? super T>> in the method signature but its not I see in any method signature. Access modifier, static or not ,return type, name of method are known to me, but what is the extra one?

Update : I was not aware of this : "All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type"

here's the complete signature :

public static <T extends Comparable<? super T>> void sort(List<T> list)

as you can see T must implement Comparable otherwise how will sort() know how to sort the List<T>

public static <T extends Comparable<? super T>> void sort(List<T> list) 

If you don't know which employee is greater than the other you can't sort. Just add in a custom Comparator.

For primitive data types such as int, long, float etc the comparison is pre defined. And sort takes in the predefined comparison measures and sorts your variables.

However, when you make a class, a class can be composed of many different primitive types and even other objects. Java cannot automatically know how to compare and so it needs to extend the comparable interface and define functions that specify how to sort. For eg

Class car {
int id; 
String name;
String company;
}

After implementing comparable you can define if your sorting depends on the id of the cars, its name or company name. Hope this clears the need a bit.

With generics, there are two approaches: 1. Wild cards and 2.Bounded type parameter.

Example with Wild cards : public void sort(List<? extends T> list)

Example with Bounded type : public static <T extends Comparable<? super T>> void sort(List<T> list) public static <T extends Comparable<? super T>> void sort(List<T> list)

Bounded type is preferred when `T needs to be used more than once, like in the above example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM