set (int index Object element) method of List Interface in java.

set (int index Object element) method of List Interface in java.


Posted in : Core Java Posted on : January 12, 2011 at 5:32 PM Comments : [ 0 ]

In this section we will show you how can you replace specified element at specified position in a list.

set (int index Object element) method of List Interface in java.

In this section we will show you how can you replace specified element at specified position in a list.

Syntax 

public Object set (int index Object element)

This method returns the previous element of that specified position which was replaced by the new element.

In this method you can set specified element at the specified position. In other word we can say that, can replace a new element with previously existing element in a list. This method returns that element which was just replaced by new element. Through this method you can remove an old value from specified position and put the new value at the same position. 

Parameter Description

int index : It takes an argument as index (integer value) at which position do you want to set value.

Object element : It takes an argument as element by which do you want to replace with an existing element in a list.

Example of set (int index Object element) method

In this example we will show you how does set (int index Object element) method works in List interface. This example will help you to understand how can you replace an element with an existing element in a list at specified position. Through this example we will show you adding of element to the list, size of list,  and replacement of an element at specified position.

Example:-

package Devmanuals.com;
import java.util.List;
import java.util.ArrayList;
public class ListSetIndex {
public static void main (String args []){
Object obj;
ArrayList al=new ArrayList();
al.add("Dev");
al.add("Manuals");
al.add("Network");
System.out.println("List is : "+al);
System.out.println("Size of list : "+al.size());
obj=al.set(2, ".com");
System.out.println("Now we replace " +obj+ " by " +al.get(2));
System.out.println("Then new List will be : "+al);
System.out.println("Size of list : "+al.size());
}
}

Output :

List is : [Dev, Manuals, Network]

Size of list : 3

Now we replace Network by .com

Then new List will be : [Dev, Manuals, .com]

Size of list : 3

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics