The sort methods for collections specifies that the parameter must be a collection of objects that implement Comparable for their own class or superclass, eg

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

Can anyone tell me how to define an ArrayList that will only accept such objects?
I want to say

ArrayList<T extends Comparable<? super T>>  eg = new ArrayList<String>();

But that doesn't compile. I could use

ArrayList<? extends Comparable<?>> ok = new ArrayList<String>();

but that's a bit too general (although the exceptions would be weird anyway).
I know I'm going to look silly when someone points out the obvious answer, but please do it anyway.

AFAIK, not possible since there is nothing which can be used to infer the type T in there. I'm assuming here that the aim is to ensure a Collection satisfies a given criteria. In that case, the simplest solution would be to create a separate method for the piece of code which relies on the above assumption and have the method signature same as that of the Collections.sort method.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.