Saturday 4 May 2013

Collections Example(ArrayList)

Before we dive further into Collections let me take an example to show how Collections actually work.Lets take an List example as it is the most simple to understand. You can then try similar operations on Set and Queue. Not the functions remain the same for all as all three implement Collection interface. Only their implementations will vary.

Code

package testCodes;

import java.util.ArrayList;
import java.util.List;

public class ListDemo {

    public static void main(String[] args) {

        List<String> nameList = new ArrayList<String>();
        nameList.add("John");
        nameList.add("Sam");
        System.out.println(nameList);
        nameList.add(0, "kenny");
        System.out.println("Size of list is " + nameList.size());
        System.out.println(nameList);
        nameList.remove("Sam");
        System.out.println(nameList);
        nameList.remove(0);
        System.out.println(nameList);
        System.out.println("Size of list is " + nameList.size());
    }
}

Output 


Explanation

   First we create a List name nameList and then populate it with some values.Not the use of polymorphism(Superclass reference i.e List to subclass object i.e ArrayList).  You can add values in any Collection using .add() method.Observer the .add(0, "kenny") method. You can specify index as the 1st argument. Since i have put 0 "Kenny" is added to the front of the list(index 0). .remove() is also similar. Either you can specify an object to be removed as an argument or index at which object is to be removed. You can print the size of collection using .size() method. There are various other methods in Collection that we will learn in time but for now these should suffice. You can now play around with other Collections like Set and Queue

.clear() is another simple method to try. It will simple remove all emenets from the Collection. After this if you do .size() you will get 0.

No comments:

Post a Comment

t> UA-39527780-1 back to top