Java中的LinkedList set()方法

Java中的LinkedList set()方法

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

语法:

LinkedList.set(int index, Object element)

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

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

返回值: 该方法返回从替换为新值的链接列表中替换的先前值。下面的程序说明Java.util.LinkedList.set()方法:

例1:

// Java code to illustrate set() Method
 
// Importing required libraries
import java.io.*;
import java.util.LinkedList;
 
// Class
public class LinkedListDemo {
 
    // Main driver method
    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]

在Java中,set(int index, E element)方法用于将LinkedList的元素在指定的索引处设置为新元素。该方法将指定索引处的现有元素替换为新元素。

例2: 以下是如何使用set()方法的示例

import java.util.LinkedList;
 
public class LinkedListExample
 
public static void main(String[] args)
{
    // Create a LinkedList of Strings
    LinkedList<String> list = new LinkedList<String>();
    list.add("apple");
    list.add("banana");
    list.add("cherry");
    list.add("date");
    list.add("elderberry");
 
    // Replace an element in the LinkedList
    list.set(2, "grape");
 
    // Print the updated LinkedList
    System.out.println("LinkedList after replacement: "
                       + list);
}
}

输出

LinkedList after replacement: [apple, banana, grape, date, elderberry]

在本示例中,首先创建了名为list的五个元素的字符串LinkedList。然后使用set()方法将索引2处的元素替换为“grape”。LinkedList中元素的索引从0开始。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程