Showing posts with label collections. Show all posts
Showing posts with label collections. Show all posts

Tuesday, October 15, 2013

toArray Dynamic behaviour

public class ToArrayTest {

public static void main(String[] args) {

ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");

//what happens here??, since I have allocated new String[0] for single element, will it return single element or all elements ??
String[] array = arrayList.toArray(new String[0]); 
System.out.println(array.length);

}
}


Output:  4


As per spec, it's going to create a new array, if it does not fit in.
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list. 

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