Java Stack addAll(int, Collection)方法及示例

Java Stack addAll(int, Collection)方法及示例

堆栈类的addAll(int, Collection)方法用于将作为参数传递给该函数的集合中的所有元素追加到一个堆栈的特定索引或位置。

语法

boolean addAll(int index, Collection C)

参数: 该函数接受两个参数,如上述语法所示,描述如下。

  • index :这个参数是整数数据类型,指定了堆栈中的位置,从那里开始,容器中的元素将被插入。
  • C :它是一个ArrayList的集合。它是一个需要添加元素的集合。

返回值: 如果至少有一个append的动作被执行,该方法返回True,否则返回False。

下面的程序说明了Java.util.Stack.addAll()方法。

例1:

// Java code to illustrate boolean addAll()
  
import java.util.*;
import java.util.ArrayList;
  
public class GFG {
    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");
  
        // A collection is created
        Collection<String> c = new ArrayList<String>();
        c.add("A");
        c.add("Computer");
        c.add("Portal");
        c.add("for");
        c.add("Geeks");
  
        // Displaying the Stack
        System.out.println("The Stack is: " + stack);
  
        // Appending the collection to the Stack
        stack.addAll(1, c);
  
        // Clearing the Stack using clear() and displaying
        System.out.println("The new Stack is: " + stack);
    }
}

输出:

The Stack is: [Geeks, for, Geeks, 10, 20]
The new Stack is: [Geeks, A, Computer, Portal, for, Geeks, for, Geeks, 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);
  
        // A collection is created
        Collection<Integer> c = new ArrayList<Integer>();
        c.add(1);
        c.add(2);
        c.add(3);
  
        // Displaying the Stack
        System.out.println("The Stack is: " + stack);
  
        // Appending the collection to the Stack
        stack.addAll(2, c);
  
        // Clearing the Stack using clear() and displaying
        System.out.println("The new Stack is: " + stack);
    }
}

输出:

The Stack is: [10, 20, 30, 40, 50]
The new Stack is: [10, 20, 1, 2, 3, 30, 40, 50]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程