在Java中使用示例堆栈 insertElementAt() 方法
Java.util.Stack.insertElementAt(element, index)方法用于在堆栈的指定索引处插入特定元素。元素和位置都作为参数传递。如果在指定索引处插入一个元素,则所有元素都会向上推 1,因此容量会增加,从而为新元素创建空间。
句法:
Stack.insertElementAt()
参数:该方法接受两个参数:
- element:这是需要插入到堆栈中的元素。
- index:这是整数类型,指的是要插入新元素的位置。
返回值:该方法不返回任何内容。
异常:如果索引是无效数字,该方法将抛出ArrayIndexOutOfBoundsException 。
下面的程序说明了Java.util.Stack.insertElementAt() 方法:
程序 1:将字符串元素添加到堆栈中。
Java
// Java code to illustrate insertElementAt()
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack stack = new Stack();
// Use add() method to add elements into the Stack
stack.add("Welcome");
stack.add("To");
stack.add("Geeks");
stack.add("4");
stack.add("Geeks");
// Displaying the Stack
System.out.println("Stack: " + stack);
// Inserting element at 3rd position
stack.insertElementAt("Hello", 2);
// Inserting element at last position
stack.insertElementAt("World", 6);
// Displaying the final Stack
System.out.println("The final Stack is "
+ stack);
}
}
Java
// Java code to illustrate insertElementAt()
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack stack = new Stack();
// Use add() method to add elements into the Stack
stack.add(10);
stack.add(20);
stack.add(30);
stack.add(40);
stack.add(50);
// Displaying the Stack
System.out.println("Stack: " + stack);
// Inserting element at 1st position
stack.insertElementAt(100, 0);
// Inserting element at fifth position
stack.insertElementAt(200, 4);
// Displaying the final Stack
System.out.println("The final Stack is "
+ stack);
}
}
输出:
Stack: [Welcome, To, Geeks, 4, Geeks]
The final Stack is [Welcome, To, Hello, Geeks, 4, Geeks, World]
程序 2:将整数元素添加到堆栈中。
Java
// Java code to illustrate insertElementAt()
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack stack = new Stack();
// Use add() method to add elements into the Stack
stack.add(10);
stack.add(20);
stack.add(30);
stack.add(40);
stack.add(50);
// Displaying the Stack
System.out.println("Stack: " + stack);
// Inserting element at 1st position
stack.insertElementAt(100, 0);
// Inserting element at fifth position
stack.insertElementAt(200, 4);
// Displaying the final Stack
System.out.println("The final Stack is "
+ stack);
}
}
输出:
Stack: [10, 20, 30, 40, 50]
The final Stack is [100, 10, 20, 30, 200, 40, 50]