get(int index) method of List Interface in java.

get(int index) method of List Interface in java.


Posted in : Core Java Posted on : January 5, 2011 at 7:04 PM Comments : [ 0 ]

In the following example we will show you the method of finding element from the list using get(int index) method of List Interface in java.

get(int index) method of List Interface in java.

In the following example we will show you the method of finding element from the list using get(int index) method of List Interface in java.

Syntax

public object get(int index)

This method gives the element from the specified position.

In this method you can find an element from the list. It gives the element from the specified position from the specified list. It can be give only those elements which are present in index of the list. This method does not returns the element if the index is greater than the size of list. In other word we can say if the index is out of range then it will not be return the element and throws the exception IndexOutOfBoundsException. 

Parameter Description

int index : It takes an argument as integer value for the index number of list.

Example of get(int index) method 

In this example we will show you how does get(int index) method works in List interface. This example will help you to understand how can you find an element from the list at the specified position. Through this example we will show you adding of element to the list, count the number of list, get the element of list with their position value, first and last position value.

Example:-



package Devmanuals.com;
import java.util.ArrayList;
public class ListGetIndex{
public static void main (String []args){
ArrayList al = new ArrayList();
al.add("Java");
al.add("Collection");
al.add("List");
al.add("Interface");
System.out.println("Elements of list are : "+al);
System.out.println("Size of list = "+al.size());
//Getting all the elements of a list with their index value
for(int i=0;i<al.size();i++)
System.out.println("Element at the position " +i+"=" +al.get(i));
//Getting the element of a list at the position '0'
System.out.println("");
System.out.println("Element at the position "+(al.size()-al.size())+"="+al.get((al.size()-al.size())) );
//Getting the element of a list at the position 'last'
System.out.println("Element at the last position " +(al.size()-1) +"="+al.get(al.size()-1));
}
}

Output :

Elements of list are : [Java, Collection, List, Interface]

Size of list = 4

Element at the position 0=Java

Element at the position 1=Collection

Element at the position 2=List

Element at the position 3=Interface

Element at the first position 0=Java

Element at the last position 3=Interface

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics