📜  Java中的堆栈add(int,Object)方法与示例

📅  最后修改于: 2022-05-13 01:54:52.617000             🧑  作者: Mango

Java中的堆栈add(int,Object)方法与示例

Stack 类add(int, Object)方法在 Stack 的指定索引处插入一个元素。它将当前位于该位置的元素(如果有)和任何后续元素向右移动(将通过添加一个来更改它们的索引)。

句法:

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 stack = new Stack();
  
        // 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 stack
            = new Stack();
  
        // 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]