Wednesday, November 28, 2012

Collections emptyList()

Can you guess the output for the below program ?
import java.util.Collections;
import java.util.List;

public class CollectionsTest {

private List<String> pool = Collections.<String> emptyList();

public List<String> call1() {
pool.add("Hello");
return pool;
}

public static void main(String[] args) {
CollectionsTest collectionsTest = new CollectionsTest();
List<String> call1 = collectionsTest.call1();
System.out.println(call1);
call1.add("one more added..");
System.out.println(call1);
}
}


Output:

Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:131)
at java.util.AbstractList.add(AbstractList.java:91)
at CollectionsTest.call1(CollectionsTest.java:9)
at CollectionsTest.main(CollectionsTest.java:15)


In short:
Collections.emptyList() returns an immutable list, i.e., a list to which you cannot add or remove elements.

Then, why should we use at all ? What is the purpose of this ?


Best Regards,
Kondal Kolipaka


No comments:

Post a Comment