.set()
DavidDemetradze1 total contribution
Published Jan 19, 2023
Contribute to Docs
The .set()
method replaces an element at a specified position with another element in an ArrayList
instance. After execution, the replaced element is returned.
Syntax
arrayListInstance.set(index, newElement);
An element at a specified index
is replaced in an arrayListInstance
with the newElement
.
Note: The
newElement
must be of the same data type as the rest of the elements inarrayListInstance
. Otherwise, an error will occur.
Example
In the example below, an empty ArrayList
instance studentList
is created and can hold String
-type elements. Next, a few elements are added with the .add()
method. Lastly, two students are replaced with the .set()
method:
import java.util.ArrayList;public class Students {public static void main(String[] args) {ArrayList<String> studentList = new ArrayList<String>();// Add new values to the studentListstudentList.add("John");studentList.add("Lily");studentList.add("Samantha");studentList.add("Tony");// `.set()` method returns replaced element's valueString replacedStudentOne = studentList.set(1, "David");String replacedStudentTwo = studentList.set(2, "George");// Output updated ArrayList and replaced elementsSystem.out.println("Updated ArrayList: " + studentList);System.out.println("Replaced Elements: " + replacedStudentOne + " and " + replacedStudentTwo);}}
The output should look like this:
Updated ArrayList: [John, David, George, Tony]Replaced Elements: Lily and Samantha
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.