Saturday, April 18, 2009

secrets of list class part 1: constructor tricks

List classes in Java can be thought as resizable arrays. They are very frequently used as they are handy. In this part of the article, I'll show you two constructor tricks that can become quite useful in special cases. The first trick is for using an existing list content for creating a new list. The second trick is for ensuring the element capacity of a list. You can ask yourself why are we giving a capacity value to a list if it can increase its capacity by itself. The answer is that yes, lists can increase their capacity by themselves but if we know the potential size we can skip waiting for the initial capacity adjustment and save some precious time. Here's the code for constructor tricks:

/* create two Integer objects which are wrappers for integers */

Integer integer1 = new Integer(1);
Integer integer2 = new Integer(2);

/* create an ArrayList and add both objects to list1*/

List list1 = new ArrayList();

// constructor tricks begin

/* to create a new list (list2) with elements of a list (list1)
* give list1 to the constructor of list2 while creating list2

List list2 = new ArrayList(list1);

// you can see that their content are the same


* we know that a large number of elements will be added to the list
* so the initial capacity of 10 will not be enough and
* the list will have to expand.
* if we have an idea about the potential initial size for a list
* we can ensure that the list's initial capacity will be large
* enough to handle the initial size of elements.
* */

final int potentialSize = 10000;

/* to create a list of desired capacity, give the capacity value
to its constructor */

List list3 = new ArrayList(potentialSize);

// add all elements to list3

for(int i=0 ; i < tmpinteger =" new">