当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java AbstractList set()用法及代码示例


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

用法:

AbstractList.set(int index, Object element)

参数:该函数接受两个参数,如下所述:

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

返回值:该方法从抽象列表中返回被新值替换的先前值。

以下示例程序旨在说明 AbstractList.set() 方法:




// Java code to illustrate set()
  
import java.util.*;
import java.util.LinkedList;
  
public class AbstractListDemo {
    public static void main(String args[])
    {
  
        // Creating an empty AbstractList
        AbstractList<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 AbstractList
        System.out.println("AbstractList:" + 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 AbstractList
        System.out.println("The new AbstractList is:" + list);
    }
}
输出:
AbstractList:[Geeks, for, Geeks, 10, 20]
The Object that is replaced is:Geeks
The Object that is replaced is:20
The new AbstractList is:[Geeks, for, GFG, 10, 50]

程序2:


// Java code to illustrate set()
  
import java.util.*;
  
public class LinkedListDemo {
    public static void main(String args[])
    {
  
        // Creating an empty AbstractList
        AbstractList<Integer>
            list = new LinkedList<Integer>();
  
        // Use add() method to add elements in the list
        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);
  
        // Displaying the AbstractList
        System.out.println("AbstractList:" + list);
  
        // Using set() method to replace 10 with 100
        System.out.println("The Object that is replaced is:"
                           + list.set(0, 100));
  
        // Using set() method to replace 20 with 200
        System.out.println("The Object that is replaced is:"
                           + list.set(1, 200));
  
        // Displaying the modified AbstractList
        System.out.println("The new AbstractList is:" + list);
    }
}
输出:
AbstractList:[10, 20, 30, 40, 50]
The Object that is replaced is:10
The Object that is replaced is:20
The new AbstractList is:[100, 200, 30, 40, 50]




相关用法


注:本文由纯净天空筛选整理自Chinmoy Lenka大神的英文原创作品 AbstractList set() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。