简体   繁体   English

如何声明每个实现的对象的Java List Comparable

[英]How to declare Java List of Object where each one implements Comparable

Here is the situation... 这是情况...

I have a List<Object> where I have to pass it around into fairly generic parts of my code. 我有一个List<Object> ,必须将其传递到代码的相当通用的部分。 In some parts, the list needs to be sorted. 在某些部分中,列表需要排序。

I will NOT know upfront what type of object is in the list. 我不会预先知道列表中是什么类型的对象。 However, by how this list is used, I am guaranteed that the contract of Comparable such that each item in the list is of the same type and is able to be compared to each other. 但是,通过使用此列表的方式,我保证Comparable的合同使列表中的每个项目都是同一类型,并且可以相互比较。

In other words, in some cases, the real type will end up being String , in other cases, Date . 换句话说,在某些情况下,实际类型最终将为String ,而在其他情况下,则为Date In yet other cases, something Custom that implements Comparable<Custom> . 在另一些情况下,一些Custom认为implements Comparable<Custom>

However, in every case, if the real type is String , all of the items in the list will be of type String . 但是,在每种情况下,如果实际类型为String ,则列表中的所有项目都将为String类型。

Let me be more specific to improve this question a bit... 让我更具体地说明一下这个问题...

Here is a class I am working on: 这是我正在研究的课程:

public class Thing {
   private Map<String, List<SourcedValue<Object>>> properties;
}

Then, SourcedValue is this: 然后, SourcedValue是这样的:

public class SourcedValue<T> {
  private T value;
  private List<Sources> sources;
}

So, how do you suggest I declare this? 那么,您如何建议我宣布这一点?

You need all of the elements of the list to be Comparable , but not just Comparable , comparable to each other. 您需要列表中的所有元素都是Comparable ,而不仅仅是Comparable ,彼此可比。 The way to enforce this at a method level is to declare a type variable with a bound of Comparable to itself. 在方法级别实施此方法的方法是声明一个类型变量,其自身具有Comparable Because a Comparable acts as a consumer, PECS (producer extends, consumer super) suggests to have a lower bound on the type argument of Comparable itself. 由于Comparable充当消费者,因此PECS(生产者扩展,消费者超级)建议对Comparable本身的类型参数定下限。

public <T extends Comparable<? super T>> void yourMethod(List<T> list) {
     // Your implementation here.
}

Depending on your exact situation, the type variable T may be on a class instead of a method. 根据您的实际情况,类型变量T可能在类而不是方法上。

public class YourClass<T extends Comparable<? super T>> {
    public void yourMethod(List<T> list) {
         // Your implementation here.
    }
}

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

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