简体   繁体   中英

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. 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.

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> .

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...

Here is a class I am working on:

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

Then, SourcedValue is this:

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. 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.
}

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.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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