Java LinkedList对象的set(int index,Object o)方法和示例
LinkedList对象set(intindex,Objecto)方法
包java.util.LinkedList.set(intindex,Objecto)中提供了此方法。
此方法用于用链接列表中的指定元素替换索引元素。
此方法用于在指定位置设置新元素。
语法:
Object set(int index , Object o){
}参数:
我们可以在方法中传递两个对象作为参数,第一个对象是索引(即,它是整数或数字类型,是指要从链表中替换的元素的位置。),第二个参数是Object(即,它是插入的元素,通过该元素将替换现有的链表。)
返回值:
此方法的返回类型为Object,这意味着此方法返回链表的旧元素或上一个元素,并用新元素替换。
Java程序演示LinkedListset()方法的示例
import java.util.LinkedList;
public class LinkList {
public static void main(String[] args) {
LinkedList list = new LinkedList();
//使用add()方法在列表中添加元素
list.add("J");
list.add("A");
list.add("V");
list.add("A");
list.add("LANGUAGE");
//当前列表输出
System.out.println("The Current list is:" + list);
//在指定位置用新元素替换旧元素
//通过实现链表的set(intindex,Objecto)。
System.out.println("The previous element (replaced with the new element) of the linked list is:" + list.set(4, "PROGRAMMING"));
//在set(intindex,Objecto)之后显示链接列表。
System.out.println("The new linked list after set(int index, Object o) is:" + list);
}
}输出结果
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]