Friday, February 18, 2022

Stack Basics

 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;

public class Stack_Basics {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
System.out.println(stack.push(1)); // it returns the number pushed
System.out.println(stack.add(2)); // it returns true
stack.push(3);
stack.push(4);
stack.push(5);

System.out.println(stack); // o/p: [1, 2, 3, 4]
System.out.println(stack.peek()); // o/p: 4
for (int x : stack) {
System.out.print(x + "\t"); // o/p: 1 2 3 4
}
System.out.println();
//Exception in thread "main" java.util.ConcurrentModificationException
// at java.util.Vector$Itr.checkForComodification(Vector.java:1212)
// at java.util.Vector$Itr.next(Vector.java:1165)
// at pep.Day25.Stack_Basics.main(Stack_Basics.java:19)
for (int x : stack)
System.out.println(stack.pop());


for each loop calculates the size first and iterates that many number of times, while execution if there is any modification in size then, it gives ConcurrentModificationException. Similarly in ArrayList.

Henceto remove elements we should use for loop, instead of foreach loop


ArrayList<Integer> arr = new ArrayList(Arrays.asList(1, 2, 3));
for (int x:arr)
System.out.println(arr.remove(x));

No comments:

Post a Comment

Popular Posts

Most Featured Post

GitHub: Squash all commits in PR

  Command Meaning git fetch origin Get the latest origin/master . git reset --soft origin/master Move your branch to match origin/master , b...