Java Stack add(int, Object)方法与实例
堆栈类的add(int, Object)方法在堆栈的指定索引处插入了一个元素。它将当前位于该位置的元素(如果有的话)和任何后续元素向右移动(将通过增加一个来改变它们的索引)。
语法
void add(int index, Object element)
参数: 该方法接受两个参数,如下所述。
- index: 要插入指定元素的索引。
- element : 需要被插入的元素。
返回值: 这个方法不返回任何值。
异常: 如果指定的索引超出了堆栈的大小范围,该方法会抛出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]
极客教程