Sunday, December 20, 2009

Why use ArrayList implementation of List?

Using ArrayList as a choice List implementation is like second nature in case of a lot of developers. We are so gotten used to picking ArrayList that we sometime forget why exactly we use the ArrayList implementation.

Here is an example of a driver program which uses ArrayList to add different objects in List and then display them.

This program's purpose is to demo the fact that ArrayList is used for the purpose of being able to add and maintain a list of different type of objects.

A couple other benefit of using ArrayList is
1. We don't need to know the total number of elements to be stored in advance.
2. The elements are accessible for any of the add/delete etc operations from anywhere in the list. In other words, each element in the ArrayList are directly accessible with an index number.

/**
* @author nsingh
*
*/

public class ListDifferentObjectTypes {
public static void main(String args[]){
List<Object> listObj = new ArrayList<Object>();
for(int i=0;i<4;i ){
AnotherObject anotherObject = new AnotherObject();
OneObject oneObject = new OneObject();
anotherObject.setLocatinType("someType" i "");
oneObject.setMessage("Message #" i "");
oneObject.setMessageId("MessageId" i "");
listObj.add(oneObject);
listObj.add(anotherObject);
}
for (Iterator iterator = listObj.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
if(object instanceof OneObject){
OneObject oneObj= (OneObject)object;
System.out.println(oneObj.getMessageId());
System.out.println(oneObj.getMessage());
}
if(object instanceof AnotherObject){
AnotherObject anotherObj = (AnotherObject)object;
System.out.println(anotherObj.getLocatinType());
System.out.println(anotherObj.getLocatinType());
}
}
}
}


//one of the objects


/**
* This class is used set a string message,
* and convert object of this type to json.
* @author nsingh
*
*/

public class OneObject {

private String messageId;
private String message;
/**
* @return the messageId
*/
public String getMessageId() {
return this.messageId;
}
/**
* @param messageId the messageId to set
*/
public void setMessageId(String messageId) {
this.messageId = messageId;
}
/**
* @return the message
*/
public String getMessage() {
return this.message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}

}


//another object
/**
* @author nsingh
*
*/

public class AnotherObject {

private String locatinType;

/**
* @return the locatinType
*/
public String getLocatinType() {
return this.locatinType;
}

/**
* @param locatinType the locatinType to set
*/
public void setLocatinType(String locatinType) {
this.locatinType = locatinType;
}
}