list.set java
The java.util.ArrayList.set(int index, E element) replaces the element at the specified position in this list with the specified element. Show DeclarationFollowing is the declaration for java.util.ArrayList.set() method public E set(int index, E element)Parameters
Return ValueThis method returns the element previously at the specified position. ExceptionIndexOutOfBoundsException − If the index is out of range ExampleThe following example shows the usage of java.util.Arraylist.set() method. package com.tutorialspoint; import java.util.ArrayList; public class ArrayListDemo { public static void main(String[] args) { // create an empty arraylist with an initial capacity ArrayListLet us compile and run the above program, this will produce the following result − Number = 15 Number = 20 Number = 25 Number = 22 Printing new list: Number = 15 Number = 20 Number = 55 Number = 22java_util_arraylist.htm
We're sorry, but the page you were looking for doesn't exist.
Here are some useful links
The syntax of the set() method is: arraylist.set(int index, E element)Here, arraylist is an object of the ArrayList class. set() ParametersThe set() method takes two parameters.
set() Return Values
Example 1: Replace an Element in ArrayListimport java.util.ArrayList; class Main { public static void main(String[] args) { // create an ArrayList ArrayListOutput In the above example, we have created an arraylist named languages. Here, we have used the set() method to replace the element at index 1 (English) with Java. Note: If you are not sure about the index number of an element, you can use the ArrayList indexOf() method. ArrayList set() Vs. add()The syntax of the add() and set() method looks quite similar. // syntax of add() arraylist.add(int index, E element) // syntax of set() arraylist.set(int index, E element)And, both the methods are adding a new element to the arraylist. This is why some people consider both methods similar. However, there is a major difference between them.
Example 2: ArrayList set() Vs. add()import java.util.ArrayList; class Main { public static void main(String[] args) { // create an ArrayList ArrayListOutput ArrayList: [Python, English, JavaScript] ArrayList after set(): [Python, Java, JavaScript] ArrayList after add(): [Python, Java, English, JavaScript]In the above example, we have created two arraylists named languages1 and languages2. We have used the ArrayList addAll() method so that both arraylists have the same elements. Here,
To learn more about adding value, visit Java ArrayList add().
Submit a bug or feature |