What do you call the position of an element in an ArrayList?

1. ArrayList get[] Method

ArrayList.get[int index] method returns the element at the specified position 'index' in the list.

1.1. Syntax

public Object get[ int index ];

1.2. Method Parameter

index – index of the element to return. A valid index is always be between 0 [inclusive] to the size of ArrayList [exclusive].

For example, if ArrayList holds 10 objects then a valid argument index will be between 0 to 9 [both inclusive].

1.3. Return Value

The get[] method returns the reference of the object present at the specified index.

1.4. IndexOutOfBoundsException

An invalid index argument will cause IndexOutOfBoundsException error.

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4 at java.util.ArrayList.rangeCheck[ArrayList.java:653] at java.util.ArrayList.get[ArrayList.java:429] at com.howtodoinjava.example.ArrayListExample.main[ArrayListExample.java:12]

Method indexOf[] Signature

public int indexOf[Object o]

This method returns -1 if the specified element is not present in the list.

ArrayList get[index] Method in Java with Examples

The get[] method of ArrayList in Java is used to get the element of a specified index within the list.

Syntax:

get[index]

Parameter:Index of the elements to be returned. It is of data-type int.

Return Type:The element at the specified index in the given list.

Exception:It throws IndexOutOfBoundsException if the index is out of range [index=size[]]



Note: Time Complexity: ArrayList is one of the List implementations built a top an array. Hence, get[index] is always a constant time O[1] operation.

Example:

Java




// Java Program to Demonstrate the working of
// get[] method in ArrayList
// Importing ArrayList class
import java.util.ArrayList;
// Main class
public class GFG {
// Main driver method
public static void main[String[] args]
{
// Creating an Empty Integer ArrayList
ArrayList arr = new ArrayList[4];
// Using add[] to initialize values
// [10, 20, 30, 40]
arr.add[10];
arr.add[20];
arr.add[30];
arr.add[40];
// Printing elements of list
System.out.println["List: " + arr];
// Getting element at index 2
int element = arr.get[2];
// Displaying element at specified index
// on console inside list
System.out.println["the element at index 2 is "
+ element];
}
}
Output List: [10, 20, 30, 40] the element at index 2 is 30

Example 2: Program to demonstrate the error

Java




// Java Program to Demonstrate Error Generated
// while using get[] method in ArrayList
// Importing ArrayList class
import java.util.ArrayList;
// Main class
public class GFG {
// Main driver method
public static void main[String[] args]
{
// Creating an Empty Integer ArrayList
ArrayList arr = new ArrayList[4];
// Using add[] method to insert elements
// and adding custom values
arr.add[10];
arr.add[20];
arr.add[30];
arr.add[40];
// Getting element at index 2
int element = arr.get[5];
// Print all the elements of ArrayList
System.out.println["the element at index 2 is "
+ element];
}
}

Output :

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 4 at java.util.ArrayList.rangeCheck[ArrayList.java:657] at java.util.ArrayList.get[ArrayList.java:433] at GFG.main[GFG.java:22]




Article Tags :
Java
Java - util package
Java-ArrayList
Java-Collections
Java-Functions
Practice Tags :
Java
Java-Collections
Read Full Article

Java.util.Arraylist.indexOf[] in Java

The indexOf[] method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Syntax :

public int IndexOf[Object o] obj : The element to search for.




// Java code to demonstrate the working of
// indexOf in ArrayList
// for ArrayList functions
import java.util.ArrayList;
public class IndexOfEx {
public static void main[String[] args] {
// creating an Empty Integer ArrayList
ArrayList arr = new ArrayList[5];
// using add[] to initialize values
arr.add[1];
arr.add[2];
arr.add[3];
arr.add[4];
// printing initial value
System.out.print["The initial values in ArrayList are : "];
for [Integer value : arr] {
System.out.print[value];
System.out.print[" "];
}
// using indexOf[] to find index of 3
int pos =arr.indexOf[3];
// prints 2
System.out.println["\nThe element 3 is at index : " + pos];
}
}

Output:

The initial values in ArrayList are : 1 2 3 4 The element 3 is at index : 2

Practical Application : The index functions are mostly useful to determine last or first occurrence of events, for example last occurrence of 6 in a throw of a die, or 1st occurrence of any letter in a name etc.

One more example:






// Java code to demonstrate the application of
// index functions in ArrayList
// for ArrayList functions
import java.util.ArrayList;
public class AppliIndex {
public static void main[String[] args] {
// creating an Empty Integer ArrayList
ArrayList arr = new ArrayList[10];
// using add[] to initialize dice values
arr.add[1];
arr.add[2];
arr.add[4];
arr.add[6];
arr.add[5];
arr.add[2];
arr.add[6];
arr.add[1];
arr.add[6];
arr.add[4];
// using IndexOf[] to find first index of 6
int pos1 =arr.indexOf[6];
// using lastIndexOf[] to find last index of 6
int pos2 =arr.lastIndexOf[6];
// to balance 0 based indexing
pos1 = pos1+1;
pos2 = pos2+1;
// printing first index of 6
System.out.println["The first occurrence of 6 is : " + pos1];
// printing last index of 6
System.out.println["The last occurrence of 6 is : " + pos2];
}
}

Output:

The first occurrence of 6 is : 4 The last occurrence of 6 is : 9

This article is contributed by Shambhavi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




Article Tags :
Java
Java - util package
Java-ArrayList
Java-Collections
Java-Functions
Practice Tags :
Java
Java-Collections
Read Full Article

Replacing an existing object in ArrayList

Here is an example of replacing an existing value from ArrayList in Java. In this example, I have an ArrayList of String which contains names of some of the most popular and useful books for Java programmers.

Our example replaces the 2nd element of the ArrayList by calling the ArrayList.set[1, "Introduction to Algorithms"] because the index of the array starts from zero. You should read a comprehensive course like The Complete Java Masterclass on Udemyto learn more about useful collection classes in Java, including ArrayList.




Java Program to replace elements in ArrayList

import java.util.ArrayList; import java.util.List; /* * Java Program to demonstrate how to replace existing value in * ArrayList. */ public class ArrayListSetDemo { public static void main[String[] args] { // let's create a list first List top5Books = new ArrayList[]; top5Books.add["Clean Code"]; top5Books.add["Clean Coder"]; top5Books.add["Effective Java"]; top5Books.add["Head First Java"]; top5Books.add["Head First Design patterns"]; // now, suppose you want to replace "Clean Coder" with // "Introduction to Algorithms" System.out.println["ArrayList before replace: " + top5Books]; top5Books.set[1, "Introductoin to Algorithms"]; System.out.println["ArrayList after replace: " + top5Books]; } } Output ArrayList before replace: [Clean Code, Clean Coder, Effective Java, Head First Java, Head First Design patterns] ArrayList after replace: [Clean Code, Introduction to Algorithms, Effective Java, Head First Java, Head First Design patterns]
You can see that initially, we have a list of 5 books and we have replaced the second element by calling theset[1, value] method, hence in the output, the second book which was "Clean Coder" was replaced by "Introduction to Algorithms".


That's all about how to replace existing elements of ArrayList in Java. The set[] method is perfect to replace existing values just make sure that the List you are using is not immutable. You can also use this method with any other List type like LinkedList. The time complexity is O[n] because we are doing index-based access to the element.

Other ArrayList tutorials for Java Programmers
  • How to reverse an ArrayList in Java? [example]
  • How to loop through an ArrayList in Java? [tutorial]
  • How to synchronize an ArrayList in Java? [read]
  • How to create and initialize ArrayList in the same line? [example]
  • Difference between an Array and ArrayList in Java? [answer]
  • When to use ArrayList over LinkedList in Java? [answer]
  • Difference between ArrayList and Vector in Java? [answer]
  • How to get a sublist from ArrayList in Java? [example]
  • How to remove duplicate elements from ArrayList in Java? [tutorial]
  • How to sort an ArrayList in descending order in Java? [read]
  • Difference between ArrayList and HashSet in Java? [answer]
  • Difference between ArrayList and HashMap in Java? [answer]

Thanks for reading this tutorial so far. If you like this ArrayList replace example then please share it with your friends and colleagues. If you have any questions or feedback, please drop a note.

Video liên quan

Bài Viết Liên Quan

Bài mới nhất

Chủ Đề