Java中的LinkedList set()方法

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

null

语法:

LinkedList.set(int index, Object 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]

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享