如何声明每个实现的对象的Java List Comparable [英] How to declare Java List of Object where each one implements Comparable

查看:66
本文介绍了如何声明每个实现的对象的Java List Comparable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是情况...

我有一个 List< Object> ,在这里我必须将其传递给代码的相当通用的部分.在某些部分中,列表需要排序.

I have a List<Object> where I have to pass it around into fairly generic parts of my code. In some parts, the list needs to be sorted.

我不会预先知道列表中的对象是什么类型.但是,通过使用此列表的方式,可以保证 Comparable 的约定使得列表中的每个项目都是同一类型,并且可以相互比较.

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.

换句话说,在某些情况下,实际类型最终将是 String ,在其他情况下将是 Date .在其他情况下, Custom 会实现Comparable< Custom> .

In other words, in some cases, the real type will end up being String, in other cases, Date. In yet other cases, something Custom that implements Comparable<Custom>.

但是,在情况下,如果实际类型为 String ,则列表中所有的项目将为字符串.

However, in every case, if the real type is String, all of the items in the list will be of type String.

让我更具体地说明一下这个问题...

Let me be more specific to improve this question a bit...

这是我正在上的课:

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

然后, SourcedValue 是这个:

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

那么,您如何建议我宣布这一点?

So, how do you suggest I declare this?

推荐答案

您需要列表中的所有元素都是 Comparable ,而不只是 Comparable 对彼此.在方法级别强制执行此方法的方法是声明一个类型变量,该变量的自身范围为 Comparable .因为 Comparable 充当消费者,所以 PECS(生产者扩展,消费者超级)建议在 Comparable 本身的类型参数上设置下限.

You need all of the elements of the list to be Comparable, but not just Comparable, comparable to each other. The way to enforce this at a method level is to declare a type variable with a bound of Comparable to itself. 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.

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

根据您的实际情况,类型变量 T 可能在类而不是方法上.

Depending on your exact situation, the type variable T may be on a class instead of a method.

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

这篇关于如何声明每个实现的对象的Java List Comparable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆