Java中的Stack add(int, Object)方法及示例
Stack类的add(int, Object)方法在栈中的指定索引处插入一个元素。它将当前在该位置的元素(如果有)和任何后续元素向右移动(通过添加一个索引值来改变它们的索引)。
语法:
void add(int index, Object element)
参数: 此方法接受以下两个参数的描述。
- index: 要插入指定元素的索引。
- element: 需要插入的元素。
返回值: 此方法不返回任何值。
异常: 如果指定的索引超出了Stack的大小范围,则该方法会抛出IndexOutOfBoundsException异常。
以下程序说明了java.util.Stack.add(int index, Object element)方法的工作原理:
示例:
// Java code to illustrate boolean add(Object element)
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<String> stack = new Stack<String>();
// Use add() method to add elements in the Stack
stack.add("Geeks");
stack.add("for");
stack.add("Geeks");
stack.add("10");
stack.add("20");
// Output the present Stack
System.out.println("The Stack is: " + stack);
// Adding new elements
stack.add(2, "Last");
stack.add(4, "Element");
// Printing the new Stack
System.out.println("The new Stack is: " + stack);
}
}
The Stack is: [Geeks, for, Geeks, 10, 20]
The new Stack is: [Geeks, for, Last, Geeks, Element, 10, 20]
示例2:
// Java code to illustrate
// boolean add(Object element)
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<Integer> stack
= new Stack<Integer>();
// Use add() method
// to add elements in the Stack
stack.add(10);
stack.add(20);
stack.add(30);
stack.add(40);
stack.add(50);
// Output the present Stack
System.out.println("The Stack is: "
+ stack);
// Adding new elements
stack.add(0, 100);
stack.add(3, 200);
// Printing the new Stack
System.out.println("The new Stack is: "
+ stack);
}
}
The Stack is: [10, 20, 30, 40, 50]
The new Stack is: [100, 10, 20, 200, 30, 40, 50]
极客教程