dsreddy
dsreddy

Reputation: 39

Add data to a generic collection in java

Is there any way i can add data to a generic collection in Java. For eg:-

import java.util.List;
import java.util.Vector;

public class testGenerics {
    public static void main(String args[]) {    
        Vector<? extends Number> superNumberList = null;

        // I can do this
        Vector<Integer> subList = new Vector<Integer>();
        subList.add(2);
        superNumberList = subList;

        // But i cannot do this
        // Gives the below compilation error.
        //The method add(capture#2-of ? extends Number) in the type 
        //Vector<capture#2-of ? extends Number> is not applicable for the arguments (Integer)        
        superNumberList = new Vector<Integer>();
        superNumberList.add(new Integer(4));

        superNumberList = new Vector<Float>();
        superNumberList.add(new Float(4));
    }

}

As mentioned in my comments i have compilation errors when i try to add an Integer or Float data to superNumberList.

I am able to do it , the first way , but would like to do it the second way and not sure why Java does not allow me to do it the second way.

I have a suitation where i have a super class which has this superNumberList and all the subclasses are trying to use this same variable but has different data types in this collection like Integer , Float etc.

Upvotes: 1

Views: 84

Answers (2)

Thilo
Thilo

Reputation: 262494

A Vector<? extends Number> is a Vector of an unknown Number type. As such, you cannot add anything into it.

It could be a Vector<Float>. So you cannot add an Integer.

But it could also be a Vector<Integer>. So you cannot add a Float.

The only thing you know about it is that whatever you pull out of the Vector will be a Number.


If you have a superclass that has subclasses for Integer, Float and so on, you should make the superclass generic:

class SuperClassWithVector<T extends Number>{
    protected Vector<T> myVector;
}

class FloatSubClass extends SuperClassWithVector<Float>{
   // here myVector takes Float
}

If you want a Vector that can take both Integer and Float (not sure if that is what you want), then you can use a Vector<Number>.

Upvotes: 3

pathfinderelite
pathfinderelite

Reputation: 3137

You don't need to use ? extends Number:

Vector<Number> superNumberList = null;
...
superNumberList = new Vector<Number>();
superNumberList.add(new Integer(4));
superNumberList.add(new Float(4));

Upvotes: 0

Related Questions