简体   繁体   English

有关声明可比较对象列表的Java问题

[英]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. 我想声明一个对象列表,但是我想确保所有对象都实现了Comparable接口。 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 我的目的是提供一个对象列表:1.实现Comparable接口2.都具有相同的类型

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>, the complier will give me an error. 如果我使用通配符List>,则编译器将给我一个错误。 Saying heap.get(0) cannot match heap.get(1) So I need to know the correct way to declare it. 说heap.get(0)不能匹配heap.get(1),所以我需要知道正确的声明方式。

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 泛型类型Comparable的引用应参数化

It's because you're using the raw type Comparable . 这是因为您使用的是原始类型Comparable You can try giving Comparable a wildcard type parameter: 您可以尝试为Comparable提供通配符类型参数:

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() . 并从getList()返回您的列表。

由于所有对象都是同一类型(例如fe FooType ),因此只需使用List<FooType>

Perhaps you could write a method that only takes a type that extends Comparable and returns a List of that type: 也许您可以编写一个只接受扩展Comparable类型并返回该类型List的方法:

public <T extends Comparable> List<T> getComparableList(T t) {
    List<T> heap = new ArrayList<T>();
    return heap;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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