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


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


Java.util.Vector.set()方法用于将使用Vector类创建的向量中的任何特定元素替换为另一个元素。

用法:

Vector.set(int index, Object element)

参数:该函数接受两个强制性参数,如上面的语法所示和下面的描述。


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

返回值:该方法从向量中返回被新值替换的先前值。

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

示例1:

// Java code to illustrate set() 
import java.util.*; 
  
public class VectorDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty Vector 
        Vector<String> vec_tor = new Vector<String>(); 
  
        // Use add() method to add elements in the vector 
        vec_tor.add("Geeks"); 
        vec_tor.add("for"); 
        vec_tor.add("Geeks"); 
        vec_tor.add("10"); 
        vec_tor.add("20"); 
  
        // Displaying the Vector 
        System.out.println("Vector: " + vec_tor); 
  
        // Using set() method to replace Geeks with GFG 
        System.out.println("The Object that is replaced is: "
                           + vec_tor.set(2, "GFG")); 
  
        // Using set() method to replace 20 with 50 
        System.out.println("The Object that is replaced is: "
                           + vec_tor.set(4, "50")); 
  
        // Displaying the modified vector 
        System.out.println("The new Vector is:" + vec_tor); 
    } 
}
输出:
Vector: [Geeks, for, Geeks, 10, 20]
The Object that is replaced is: Geeks
The Object that is replaced is: 20
The new Vector is:[Geeks, for, GFG, 10, 50]

示例2:

// Java code to illustrate set() 
import java.util.*; 
  
public class VectorDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty Vector 
        Vector<Integer> vec_tor = new Vector<Integer>(); 
  
        // Use add() method to add elements in the vector 
        vec_tor.add(12); 
        vec_tor.add(23); 
        vec_tor.add(22); 
        vec_tor.add(10); 
        vec_tor.add(20); 
  
        // Displaying the Vector 
        System.out.println("Vector: " + vec_tor); 
  
        // Using set() method to replace 12 with 21 
        System.out.println("The Object that is replaced is: "
                           + vec_tor.set(0, 21)); 
  
        // Using set() method to replace 20 with 50 
        System.out.println("The Object that is replaced is: "
                           + vec_tor.set(4, 50)); 
  
        // Displaying the modified vector 
        System.out.println("The new Vector is:" + vec_tor); 
    } 
}
输出:
Vector: [12, 23, 22, 10, 20]
The Object that is replaced is: 12
The Object that is replaced is: 20
The new Vector is:[21, 23, 22, 10, 50]


相关用法


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