chevron_left
996 points
8 4 3

Problem:

I was handling the ArrayList in java and learning through my mistakes.
Here I come to know that can I use an ArrayList class method to replace an item at a specific location in an ArrayList?

If it is possible,
please let me know the way or method which I can use to do this.

Solution:

I hope you are doing fine.
Yes you can make an ArrayList class method and manipulate a particular data from that list by calling a method called.set()

You need to specify the location and the string inside the method of .set() This method will modify your data from the ArrayList at your specified location of the Array. Let’s have a look into this program below:

import java.util.ArrayList;
import java.util.List;

public class SetDemo {

  public static void main(String[] args) {

    List<String> top3Footballers = new ArrayList<String>();
    top3Footballers.add("Lionel Messi");
    top3Footballers.add("Christiano Ronaldo");
    top3Footballers.add("Neymar Jr.");
    
    System.out.println("ArrayList before replace: " + top3Footballers);

    top3Footballers.set(2, "Antoine Griezmann");

    System.out.println("ArrayList after replace: " + top3Footballers);
  }

}

Here I declared an ArrayList and set the value under top3Footballers.

Later, I modified the value by using .set() method. This program will produce the output below:

ArrayList before replace: [Lionel Messi, Christiano Ronaldo, Neymar Jr.] 

ArrayList after replace: [Lionel Messi, Christiano Ronaldo, Antoine Griezmann]

I hope this helps you. Keep mistaking and learning. Thanks.

More Posts

you can use this arraylist class method to replace an item at a specific location in an arraylist. DivyaN - Aug 17
Attempt to invoke virtual method 'int.java.lang.Integer.intValue()' on a null object reference at Cast.writetoParce Sabbir Hossain - Mar 31
an arraylist object automatically expands in size to accommodate the items stored in it - Java DivyaN - Sep 3
How to read text file in java and store it to an ArrayList mhfaisal - Jul 4
How to return an ArrayList in java-[Posted] Anaiza Malik - Oct 20, 2020
add items to an arraylist java DivyaN - Aug 15
How to store multiple values in ArrayList in Java? Hafsa_Rao - Aug 5
get value from arraylist in java DivyaN - Aug 15
Difference between arraylist and linkedlist in java kesav.eee - Jun 1
Remove Duplicate elements from Arraylist in java kesav.eee - May 15