1

first post here...

Here is a generic class I have defined:

public class TimeSeries<T extends Number> extends TreeMap<Integer, T>{
     ...

     public Collection<Number> data() {
         return this.values();  
     }
}

A bit of context. TimeSeries is basically a specific kind of TreeMap, where the keys are Integers and the values are Numbers.

My issue is that the data method breaks with the following error:

error: incompatible types: Collection<T> cannot be converted to Collection<Number>
    return this.values();   
                      ^
where T is a type-variable: T extends Number declared in class TimeSeries

values method just returns a Collection of T. Why exactly can't I return this out of the method if I have specifically stated that T extends Number?

Thanks in advance.

2 Answers2

4

You have to return any of these types:

public Collection<? extends Number> data() {
    return this.values();  
}

or

public Collection<T> data() {
    return this.values();  
}

Think of it this way:

TimeSeries<Integer> series = new TimeSeries<>();

// You want this:
Collection<Number> data = series.data();

// Oops, compiles, but not an Integer:
data.add(Long.valueOf(42));

More information:

Community
  • 1
  • 1
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
1

If you wish to return Collection<Number>, you can use Collections.unmodifiableCollection to make a read-only view over Collection<T>:

public Collection<Number> data() {
    return Collections.unmodifiableCollection(this.values());
}

unmodifiableCollection and its cousins in Collections class are very handy for making read-only views as collection of supertype over collections of subtype.

Misha
  • 27,433
  • 6
  • 62
  • 78
  • @LukasEder What version of java are you using? unmodifiableCollection's signature is `static Collection unmodifiableCollection(Collection extends T> c)`. It compiles on every version of java I tried and works perfectly well. – Misha May 29 '15 at 06:44
  • Interesting, my bad. I seem to have run into an Eclipse compiler issue. Will verify, but your solution seems fine – Lukas Eder May 29 '15 at 06:51