如何在Java中替换向量的特定索引处的元素?
Vector类实现了一个可增长的对象数组。向量基本上属于遗留类,但现在它与集合完全兼容。它在Java.util包中,实现了List接口,所以这里我们可以使用List接口的所有方法。
例子
Input : Vector= ["Harry","Steve","Vince","David","Matt"],Index=1,Element ="Mark"
Output : Vector= ["Harry","Mark","Vince","David","Matt"]
Input : Vector= ["Harry","Steve","Vince","David","Matt"],Index=2,Element ="Jack"
Output : Vector= ["Harry","Mark","Jack","David","Matt"]
方法:
向量中的元素可以使用set() 方法在特定/指定索引处替换为另一个元素,或者我们可以说Java.util.Vector.set() 方法。
句法:
Vector.set(int index, Object element)
参数:此函数接受两个强制参数,如上述语法所示和下文所述。
- index :这是整数类型,指的是要从向量中替换的元素的位置。
- element :它是现有元素将被替换的新元素,并且与向量具有相同的对象类型。
返回值:该方法从被新值替换的向量中返回先前的值。
Java
// Java Program to replace a element at a particular index
// in vector
import java.util.Vector;
public class GFG {
public static void main(String[] args)
{
// making a new vector object
Vector vector = new Vector();
// adding elements to the vector.
vector.add("Harry");
vector.add("Steve");
vector.add("Vince");
vector.add("David");
vector.add("Matt");
System.out.println("Vector elements before replacement: ");
for (int i = 0; i < vector.size(); i++)
{
System.out.print(vector.get(i) + " ");
}
System.out.println();
// Replacing index 1 element
vector.set(1, "Mark");
// Replacing index 2 element
vector.set(2, "Jack");
System.out.println("Vector elements after replacement: ");
for (int i = 0; i < vector.size(); i++)
{
System.out.print(vector.get(i) + " ");
}
System.out.println();
}
}
输出
Vector elements before replacement:
Harry Steve Vince David Matt
Vector elements after replacement:
Harry Mark Jack David Matt