2

I am trying to make a generic List that can contain only Numbers. When i try to add an Integer to it, it gives the following error.

add(T) in List cannot be applied to Java.lang.Number

public class QueryHelper<T extends Number> {

    private List<T> records;

    public void query(QueryTypes queryType) {
        records = new ArrayList();
        records.add((Number)new Integer(90));        
    }
}

What is causing this problem?

Salih Erikci
  • 5,076
  • 12
  • 39
  • 69

1 Answers1

10

A List<T> where T extends Number can be a List<Number>, a List<Integer>, a List<Double>, etc...

You can't add an Integer to a List<Double>. Hence the compilation error.

If you want to be able to add any Number instance to that list, simply define it as

private List<Number> records;

which means you won't need the generic type parameter T.

Eran
  • 387,369
  • 54
  • 702
  • 768