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]
相關用法
- Java Vector add()用法及代碼示例
- Java Vector contains()用法及代碼示例
- Java Vector get()用法及代碼示例
- Java Vector remove()用法及代碼示例
- Java Vector removeElementAt()用法及代碼示例
- Java Vector elements()用法及代碼示例
- Java Vector removeAll()用法及代碼示例
- Java Vector removeIf()用法及代碼示例
- Java Vector hashCode()用法及代碼示例
- Java Vector insertElementAt()用法及代碼示例
- Java Vector firstElement()用法及代碼示例
- Java Vector size()用法及代碼示例
- Java Vector equals()用法及代碼示例
- Java Vector lastElement()用法及代碼示例
- Java Vector setSize()用法及代碼示例
注:本文由純淨天空篩選整理自kundankumarjha大神的英文原創作品 Vector set() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。