11:20 pm - Sunday February 19, 2017

Array List program for replace the element at the specified position set(int index, E element)

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

BACK

This method is used to replace the element at the specified position in Array List.

Example Program


import java.util.ArrayList;

public class ArrayListSet {
public static void main(String args[])

{
// create an arraylist
ArrayList arrlist = new ArrayList(5);
// add elements using add method
arrlist.add(10);
arrlist.add(12);
arrlist.add(15);
arrlist.add(20);
arrlist.add(23);
// print all the elements in the arraylist
System.out.println("array list:");
for (Integer num : arrlist) {
System.out.println("number:" + num);
}
// insert the element 17 at 4th position
arrlist.set(3, 17);
// print new arraylist
System.out.println("new array list:");
for (Integer num : arrlist) {
System.out.println("number=" + num);
}

}
}

Output

array list:

number:10

number:12

number:15

number:20

number:23

new array list:

number=10

number=12

number=15

number=17

number=23

Explanation:

public E set(int index, E element)

Replaces the element at the specified position in this list with the specified element.

Parameters:

index – index of the element to replace

element – element to be stored at the specified position

Returns:

the element previously at the specified position

Throws:

IndexOutOfBoundsException – if the index is out of range (index < 0 || index >= size())

 

BACK

Filed in: Java Examples

Comments are closed.