Sijo Kurien
Sijo Kurien

Reputation: 135

Adding a generic class to a list that takes generic type

I have a Field as below,

public class Field<T> {
    private T eventField;
    /**
     * @return the eventField
     */
    public T getEventField() {
        return eventField;
    }
    /**
     * @param eventField the eventField to set
     */
    public void setEventField(T eventField) {
        this.eventField = eventField;
    }
}

Now i have declared a List which takes in 'Field' of generic type 'Object'. But when i create Field of type string and try to add to the List, it fails. Please help me understand this from the underlying reason.

List<Field<Object>> l = new ArrayList<Field<Object>>();
Field<String> f = new Field<String>();
f.setEventField("Hi");

l.add(f);

Upvotes: 1

Views: 89

Answers (1)

davidxxx
davidxxx

Reputation: 131556

You declare a List of Field<Object> :

    List<Field<Object>> l = new ArrayList<Field<Object>>();

So you cannot add in a Field<String>.

You could declare

List<Field<? extends Object>> l = new ArrayList<Field<? extends Object>>();

or the shorthand version :

List<Field<?>> l = new ArrayList<Field<?>>();

and it will be valid :

 Field<String> f = new Field<String>();
 f.setEventField("Hi");
 l.add(f);

Upvotes: 3

Related Questions