CopyOnWriteArrayList get() method in Java
Last Updated :
26 Nov, 2018
The get(index) method of CopyOnWriteArrayList returns the element at the specified index.
Syntax:
public E get(int index)
Parameters: The function accepts a mandatory parameter index which specifies the index of the element to be returned.
Return Value: The function returns the element at the given index.
Exceptions: The function throws IndexOutOfBoundsException if the index is out of range.
Below programs illustrate the above function:
Program 1:
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
CopyOnWriteArrayList<Integer> ArrLis
= new CopyOnWriteArrayList<Integer>();
ArrLis.add( 32 );
ArrLis.add( 67 );
ArrLis.add( 98 );
ArrLis.add( 100 );
System.out.println( "CopyOnWriteArrayList: "
+ ArrLis);
System.out.println( "Element at 2nd index: "
+ ArrLis.get( 2 ));
}
}
|
Output:
CopyOnWriteArrayList: [32, 67, 98, 100]
Element at 2nd index: 98
Program 2:
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
CopyOnWriteArrayList<String> ArrLis
= new CopyOnWriteArrayList<String>();
ArrLis.add( "gopal" );
ArrLis.add( "gfg" );
ArrLis.add( "jgec" );
ArrLis.add( "sudo" );
System.out.println( "CopyOnWriteArrayList: "
+ ArrLis);
System.out.println( "CopyOnWriteArrayList: "
+ ArrLis.get( 4 ));
}
}
|
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at java.util.concurrent.CopyOnWriteArrayList.get(CopyOnWriteArrayList.java:388)
at java.util.concurrent.CopyOnWriteArrayList.get(CopyOnWriteArrayList.java:397)
at GFG.main(GFG.java:24)
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CopyOnWriteArrayList.html#get-int-
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...