Skip to content
Advertisement

Java Questions Regarding declaring a list of Comparable objects

It is a pretty simple one. I want to declare a list of objects, but I want make sure all objects implemented the Comparable interface. What should I do? I try to write

   List<Comparable> heap = new ArrayList<Comparable>();

But compiler gives me a warning. What is the proper way to write it?

Thanks

Follow up: I thought I had finished the question before I post it but apparently I didn’t. So let me finish it up.

My purpose is to have a list of objects that:

  1. Implements the Comparable interface
  2. Are all with the same type

Can I make it

   List<Comparable<?>> heap = new ArrayList<Comparable<?>>()

No, I can’t. The reason is because I need to retrieve the elements from the list and compare them. like:

   if( heap.get(0).compareTo(heap.get(1)) > 0)

If I use wildcard List<Comparable<?>>, the complier will give me an error. Saying heap.get(0) cannot match heap.get(1) So I need to know the correct way to declare it.

I find somebody asking me what the warning is…. that surprises me…..well, the warning is: Comparable is a raw type. References to generic type Comparable should be parameterized

Advertisement

Answer

Since all your objects are of the same type (let’s say f.e. FooType), then just use a List<FooType>.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement