Java Arraylist get() Method
What is ArrayList?
Arraylist is a part of collection frameworAk in java. It is dynamic in nature. There is no fixed size , we can add or remove an element at anytime. It is found in the java.util package. We can perform several inbuilt functions of java on arraylist like get() Function which can be found in the java.util.arraylist Package.
Here, in the page we will discuss about the Java ArrayList get() Method.
Java ArrayList get() method
In ArrayList class of java there are many inbuilt methods which we can perform on an arraylist to do different task. ArrayList get() method is one of the inbuilt method which is used to retrieve the element at a specified index. The get() method also throws an exception ‘array index out of bound’.
Syntax :
arraylist.get(int index)
Definition of parameters:
arraylist: it is the name of the arraylist on which the get() method is used. index: position of element to be accessed.
Return Type:
returns the element at the given index
Java ArrayList get() method examples:
Example 1:
import java.util.ArrayList; class Main { public static void main (String[]args) { ArrayList < String > list = new ArrayList <> (); list.add ("1"); list.add ("2"); list.add ("3"); // access element at index 1 String element = list.get (1); System.out.println ("Element at index 1: " + element); } }
Output :
Element at index 1: 2
Example 2:
package com.company; import java.util.ArrayList; public class Main { public static void main (String[]args) { ArrayList < Integer > list = new ArrayList < Integer > (); list.add (10); list.add (20); list.add (30); list.add (40); // Getting element at index 5 int element = list.get (5); System.out.println ("the element at index 5 is " + element); } }
Output :
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 5 out of bounds for length 4 at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266) at java.base/java.util.Objects.checkIndex(Objects.java:359) at java.base/java.util.ArrayList.get(ArrayList.java:427) at com.company.Main.main(Main.java:14)
What happened above?
In the above example the code is throwing an exception 'IndexOutOfBound' because the index 5 is out of bound for length 4.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment