'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:
- Implements the Comparable interface
- 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
Solution 1:[1]
Since all your objects are of the same type (let's say f.e. FooType
), then just use a List<FooType>
.
Solution 2:[2]
It's because you're using the raw type Comparable
. You can try giving Comparable
a wildcard type parameter:
List<Comparable<?>> heap = new ArrayList<Comparable<?>>();
If you want the objects to all be of the same type, you can do something along the lines of
public static <T extends Comparable<? super T>> List<T> getList() {
...
}
and return your list from getList()
.
Solution 3:[3]
Perhaps you could write a method that only takes a type that extends Comparable and returns a List of that type:
public <T extends Comparable> List<T> getComparableList(T t) {
List<T> heap = new ArrayList<T>();
return heap;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tassos Bassoukos |
Solution 2 | |
Solution 3 | user1549672 |