Nirmal
Nirmal

Reputation: 21

How to create object of Collection and add elements to it

How to create an object of Collection and add elements to it?

I did something like this :

Collection col = Collections.EmptyList();
col.add("String1");

But its throwing UnsupoortedOperationException because EmptyList() will create an immutable object which can't be changed.

Upvotes: 0

Views: 22988

Answers (4)

TanvirChowdhury
TanvirChowdhury

Reputation: 2445

you should specify type of collection.

try in this way

1.Collection<String> col = new Arraylist<>();
         col.add("String1"); 

   2.List<String> col = new ArrayList<>();
      col.add("String1");

Upvotes: 0

Devratna
Devratna

Reputation: 1008

Collection is not a concrete Object class it is just a interface, you have to create any collection concrete class that implements Collection interface like HashSet, ArrayList etc.

public static void main(String args[]) throws Exception {
        Collection col = new ArrayList<>();
        col.add("String1");
        System.out.println(col.toString());
    }

Upvotes: 0

Syed Khalid Ahmed
Syed Khalid Ahmed

Reputation: 3232

Collections.EmptyList() creates an empty list in which you cannot add more objects. you have to create by specifying type of list like :

Collection<String> col = new ArrayList<String>();
col.add("String1");

Upvotes: 2

Mr.Yellow
Mr.Yellow

Reputation: 732

Collection is just the interface for objects that store other objects. You must instantiate it with an actual implementation like a HashSet. For example:

Collection<String> col = new HashSet<String>();
col.add("String1");

Note that you must also provide the type of the object that you want to store, like String, List or Object. See the javadoc for more infos.

Upvotes: 3

Related Questions