HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions

ArrayList add/replace element at specified index in Java

By Lokesh Gupta | Filed Under: Java ArrayList

Use ArrayList.add(int index, E element) method to add element to specific index of ArrayList. To replace element at specified index, use ArrayList.set(int index, E element) method.

1. ArrayList.add(int index, E element) – Add element at specified index

This method inserts the specified element E at the specified position in this list. It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices).

Index start with 0.

public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<String> namesList = new ArrayList<String>(Arrays.asList( "alex", "brian", "charles") );
        
        System.out.println(namesList);	//list size is 3
        
        //Add element at 0 index
        namesList.add(0, "Lokesh");
        
        System.out.println(namesList);	//list size is 4
    }
}

Program output.

[alex, brian, charles]
[Lokesh, alex, brian, charles]

2. ArrayList.set(int index, E element) – Replace element at specified index

This method replaces the specified element E at the specified position in this list. As this method replaces the element, the list size does not change.

Index start with 0.

Java program to update an arraylist element. It replace element at specified index of arraylist.

public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<String> namesList = new ArrayList<String>(Arrays.asList( "alex", "brian", "charles") );
        
        System.out.println(namesList);	//list size is 3
        
        //Add element at 0 index
        namesList.set(0, "Lokesh");
        
        System.out.println(namesList);	//list size is 3
    }
}

Program output.

[alex, brian, charles]
[Lokesh, brian, charles]

3. Replace element in arraylist while iterating

Do not use iterator if you plan to modify the arraylist during iteration. Use standard for loop, and keep track of index position to check the current element. Then use this index to set the new element.

Java program to search and replace an element in an ArrayList.

public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<String> namesList = new ArrayList<String>(Arrays.asList( "alex", "brian", "charles") );
        
        System.out.println(namesList);
        
        //Replace item while iterating
        for(int i=0; i < namesList.size(); i++) 
        {
            if(namesList.get(i).equalsIgnoreCase("brian")) {
                namesList.set(i, "Lokesh");
            }
        }
        
        System.out.println(namesList);
    }
}

Program output.

[alex, brian, charles]
[alex, Lokesh, charles]

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

About Lokesh Gupta

Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.

Feedback, Discussion and Comments

  1. Steve

    February 10, 2019

    Lokesh,
    How would you replace an element based on user input?

    [0] firstName, lastName, email, phone

    So in the text file it shows [ Lokesh, Gupta, lgupta@javamaster.com, 123-123-1234]

    Thank you,
    Steve

    Reply

Ask Questions & Share Feedback Cancel reply

Your email address will not be published. Required fields are marked *

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Help me fight spammers. Solve this simple math. *

Search Tutorials

  • Email
  • Facebook
  • RSS
  • Twitter

ArrayList Methods

  • ArrayList – add()
  • ArrayList – addAll()
  • ArrayList – clear()
  • ArrayList – clone()
  • ArrayList – contains()
  • ArrayList – ensureCapacity()
  • ArrayList – forEach()
  • ArrayList – get()
  • Arraylist – indexOf()
  • Arraylist – lastIndexOf()
  • ArrayList – listIterator()
  • ArrayList – remove()
  • ArrayList – removeAll()
  • ArrayList – removeIf()
  • ArrayList – retainAll()
  • ArrayList – sort()
  • ArrayList – spliterator()
  • ArrayList – subList()
  • ArrayList – toArray()

ArrayList Examples

  • ArrayList – Initialize arraylist
  • ArrayList – Iteration
  • ArrayList – Add/replace element
  • ArrayList – Add multiple elements
  • ArrayList – Check empty list
  • ArrayList – Remove element
  • ArrayList – Replace element
  • ArrayList – Empty arraylist
  • ArrayList – Synchronized arraylist
  • ArrayList – Compare two lists
  • ArrayList – Remove duplicates
  • ArrayList – Merge two lists
  • ArrayList – Serialization
  • ArrayList – Swap two elements
  • Convert ArrayList to Array
  • Convert Array to ArrayList
  • Convert HashSet to ArrayList
  • Convert LinkedList to ArrayList
  • Convert Vector to ArrayList
  • ArrayList vs LinkedList
  • ArrayList vs Vector

Java Collections

  • Collections Framework
  • Array
  • ArrayList
  • LinkedList
  • HashMap
  • Hashtable
  • LinkedHashMap
  • TreeMap
  • HashSet
  • LinkedHashSet
  • TreeSet
  • Comparable
  • Comparator
  • Iterator
  • ListIterator
  • Spliterator
  • PriorityQueue
  • PriorityBlockingQueue
  • ArrayBlockingQueue
  • LinkedTransferQueue
  • CopyOnWriteArrayList
  • CopyOnWriteArraySet
  • Collection Sorting
  • Interview Questions

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Java Collections
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap