how to retrieve a element from an ArrayList in Collections
Previous | Home | Next |
In this example we will see how can we retrieve an element from an ArrayList.
In this example we have created a class CollectionExample. For using ArrayList we have
to import the java.util package.
In the following example we have used the get(int index) method on the ArrayList for retrieving the element stored at the specified index.
In this example we have created an ArrayList and then added a few element to it by using the add(Object obj) method on the ArrayList object. For getting the desired element we have used the get(int index) method on the ArrayList object. The following statement in the given example retrieves the element at the desired index.
al.get(2);
package r4r.co.in;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Collection;
public class CollectionExample {
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
ArrayList<String> al=new ArrayList<String>(); // creating an ArrayList named al
al.add("r4r"); // adding string objects to the arraylist
al.add("development");
al.add("tutorials");
al.add("shashi");
al.add("s/w engineer");
System.out.println("The size of the arraylist is: "+al.size()); // determining the length of the arraylist
System.out.println("The contents of the list are :"+al); // showing the contents of the arraylist
System.out.println(al.get(2)); // retrieves the element stored at index 2
System.out.println(al.contains("r4r")); // finds whether object r4r is in the arraylist or not, returns a boolean value ie, true or false
System.out.println(al.indexOf("shashi")); // displays the index of shashi
System.out.println(al.isEmpty()); // checks whether the al is empty or not, returns a bool value
}
}
The output of the above written code is as follows:
The size of the arraylist is: 5
The contents of the list are :[r4r, development, tutorials, shashi, s/w engineer]
tutorials
true
3
false
Previous | Home | Next |