Home » Java programming language

Java LinkedList Object set(int index , Object o) method with Example

Java LinkedList Object set(int index , Object o) method: Here, we are going to learn about the Object set(int index , Object o) method of LinkedList class with its syntax and example.
Submitted by Preeti Jain, on June 24, 2019

LinkedList Object set(int index , Object o) method

  • This method is available in package java.util.LinkedList.set(int index , Object o).
  • This method is used to replace the indexed element with the specified element in the linked list.
  • This method is used to sets a new element at the specified position.

Syntax:

    Object set(int index , Object o){
    }

Parameter(s):

We can pass two objects as a parameter in the method the first object is index (i.e. This is of integer or number type and refers to the position of the element that is to be replaced from the linked list.) and second parameter is Object (i.e. It is the inserted element by which the existing element will be replaced of the linked list.).

Return value:

The return type of this method is Object that means this method returns the old or previous element of the linked list that is replaced with the new element.

Java program to demonstrate example of LinkedList set() method

import java.util.LinkedList;

public class LinkList {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        // use add() method to add elements in the list 
        list.add("J");
        list.add("A");
        list.add("V");
        list.add("A");
        list.add("LANGUAGE");

        //  Current list Output
        System.out.println("The Current list is:" + list);


        // Replace old element with the new element at the specified position 
        // by implementing set(int index , Object o) of the linked list .
        System.out.println("The previous element (replaced with the new element) of the linked list is:" + list.set(4, "PROGRAMMING"));

        // Display linked list after set(int index , Object o) .
        System.out.println("The new linked list after set(int index, Object o) is:" + list);
    }
}

Output

D:\Programs>javac LinkList.java

D:\Programs>java LinkList
The Current list is:[J, A, V, A, LANGUAGE]
The previous element (replaced with the new element) of the linked list is:LANGUAGE
The new linked list after set(int index, Object o) is:[J, A, V, A, PROGRAMMING]



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.