0

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?

user1902183
  • 3,203
  • 9
  • 31
  • 48

1 Answers1

7

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.
    }
}
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • Thanks! (and yikes! I forgot how fun generics are. :-) ) Can you please edit your response, adding the edit/addition I made to the original question? This definitely looks like the right answer though for the methods/classes. – user1902183 Jun 07 '19 at 15:25
  • It's unclear how your original example pertains to your added example. – rgettman Jun 07 '19 at 16:09
  • I think I got it. Thanks! I have a followup which I will link here after I post it. – user1902183 Jun 07 '19 at 16:46
  • My followup questions is here: https://stackoverflow.com/questions/56498727/how-to-declare-java-comparable-in-this-situation – user1902183 Jun 07 '19 at 17:17