Java中, LinkedList set()的方法:Java.util.LinkedList.set()

时间:2020-07-12
本文章向大家介绍Java中, LinkedList set()的方法:Java.util.LinkedList.set(),主要包括Java中, LinkedList set()的方法:Java.util.LinkedList.set()使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
[

Java.util.LinkedList.set()方法用于将使用LinkedList类创建的链表中的任何特定元素替换为另一个元素。这可以通过指定要替换的元素的位置和set()方法的参数中的新元素来完成。

句法:

LinkedList.set(int index,Object element)

参数: 此函数接受两个参数,如上面的语法所示,如下所述。

  • index:这是整数类型,指的是要从链表中替换的元素的位置。
  • element:它是新元素,现有元素将被替换,并且与链接列表具有相同的对象类型。

返回值:该方法返回由新值替换的链接列表中的上一个值。

下面的程序说明了Java.util.LinkedList.set()方法:

// Java code to illustrate set()
import java.io.*;
import java.util.LinkedList;

public class LinkedListDemo {
    public static void main(String args[])
    {
        // Creating an empty LinkedList
        LinkedList<String> list = new LinkedList<String>();

        // Use add() method to add elements in the list
        list.add("Geeks");
        list.add("for");
        list.add("Geeks");
        list.add("10");
        list.add("20");

        // Displaying the linkedlist
        System.out.println("LinkedList:" + list);
        
        // Using set() method to replace Geeks with GFG
        System.out.println("The Object that is replaced is: " + list.set(2, "GFG"));
        
        // Using set() method to replace 20 with 50
        System.out.println("The Object that is replaced is: " + list.set(4, "50"));
        
        // Displaying the modified linkedlist
        System.out.println("The new LinkedList is:" + list);
    }
}

输出:

LinkedList:[Geeks, for, Geeks, 10, 20]
The Object that is replaced is: Geeks
The Object that is replaced is: 20
The new LinkedList is:[Geeks, for, GFG, 10, 50]
]
转载请保留页面地址:https://www.breakyizhan.com/java/4711.html

原文地址:https://www.cnblogs.com/breakyizhan/p/13287241.html