Edward
Edward

Reputation: 1377

Inserting subclass types(Integer/String) into superclass types(Object) in ArrayList

I am learning generics.

I tried below code:

For HashSet

Set<Object> setOfAnyType = new HashSet<Object>();
setOfAnyType.add(1);
setOfAnyType.add("abc"); 

But When I try same thing in ArrayList of type Object and try to insert integer and String it gives me compile time error why?.Please guide.

    List<Object> superArray=new ArrayList<Object>();
    superArray.put(1);
    superArray.put("abc");

Upvotes: 0

Views: 195

Answers (1)

Reimeus
Reimeus

Reputation: 159844

The method put is undefined for List, you can use:

superArray.add(1);
superArray.add("Sakina");

Upvotes: 4

Related Questions