Java中的Vector insertElementAt()方法及其示例

insertElementAt()方法 属于 向量类 在里面 JAVAutil包 用于在向量的指定索引处插入特定元素。元素和位置都作为参数传递。如果在指定的索引处插入一个元素,那么所有元素都会向上推一个,因此容量会增加,从而为新元素创建一个空间。

null

语法:

Vector.insertElementAt()

参数: 该方法接受两个参数:

  • 要素: 需要将其插入向量中。
  • 索引: 它指插入新元素的位置(整型)

引发异常: 数组下标越界异常 如果索引是无效的数字。

现在让我们通过为字符串元素和整数元素提供示例来添加元素,并将我们的方法应用于这两个元素,只是为了熟悉该方法在不同原始数据类型中的工作。

例1:

JAVA

// Java Program to illustrate insertElementAt()
// Method of Vector class by
// Adding String elements into the Vector
// Importing required classes
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an empty vector of string type
Vector<String> vec_tor = new Vector<String>();
// Adding custom elements into the vector
// using add() method
vec_tor.add( "Welcome" );
vec_tor.add( "To" );
vec_tor.add( "Geeks" );
vec_tor.add( "4" );
vec_tor.add( "Geeks" );
// Printing elements of vector
System.out.println( "Vector: " + vec_tor);
// Inserting element at 3rd position
// Custom specified
vec_tor.insertElementAt( "Hello" , 2 );
// Inserting element at last position
vec_tor.insertElementAt( "World" , 6 );
// Printing elements of final vector
System.out.println( "The final vector is "
+ vec_tor);
}
}


输出:

Vector: [Welcome, To, Geeks, 4, Geeks]The final vector is [Welcome, To, Hello, Geeks, 4, Geeks, World]

例2:

JAVA

// Java Program to illustrate insertElementAt()
// Method of Vector class by
// Adding Integer Elements into the Vector
// Importing required classes
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an empty Vector of integer type
Vector<Integer> vec_tor = new Vector<Integer>();
// Adding elements into the vector
// using add() method
vec_tor.add( 10 );
vec_tor.add( 20 );
vec_tor.add( 30 );
vec_tor.add( 40 );
vec_tor.add( 50 );
// Printing the current elements of vector
System.out.println( "Vector: " + vec_tor);
// Inserting element at 1st position
vec_tor.insertElementAt( 100 , 0 );
// Inserting element at 5th position
vec_tor.insertElementAt( 200 , 4 );
// Printing the final elements of Vector
System.out.println( "The final vector is "
+ vec_tor);
}
}


输出:

Vector: [10, 20, 30, 40, 50]The final vector is [100, 10, 20, 30, 200, 40, 50]

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享