Skip to content

Commit ff7d547

Browse files
committed
feat(ArrayListDemo5): show ArrayList used as a simple stack (peek, pop)
What - Added ArrayListDemo5 class. - Demonstrated how an ArrayList can be used like a stack: - push → add(E). - peek → get(size-1). - pop → remove(size-1). - Inserted elements [1,2,3]. - Called get(lastIndex) to peek at top element. - Called remove(lastIndex) to pop top element. Why - Illustrates that ArrayList can mimic stack behavior with add/get/remove at end. - Helps understand relationship between dynamic arrays and stack operations. - Shows why this is not recommended for production when java.util.Stack or Deque exists. How - ArrayLists.add(1,2,3) → list = [1,2,3]. - Peek: - ArrayLists.get(2) → returns 3 (top element). - Pop: - ArrayLists.remove(2) → removes 3, list becomes [1,2]. Logic - Inputs: integers pushed via add(). - Outputs: peek and pop values (not printed here, but executed). - Flow: 1. Add elements sequentially. 2. Peek last element with get(size-1). 3. Remove last element with remove(size-1). - Edge cases: - Calling get(size-1) or remove(size-1) on empty list throws IndexOutOfBoundsException. - Complexity: - add(E) amortized O(1). - get(size-1), remove(size-1) O(1). - Concurrency: ArrayList not thread-safe. Real-life applications - Temporary stack-like use when only last-in/first-out needed and no Stack/Deque required. - Quick demonstrations of LIFO without importing extra classes. Notes - Not recommended as best practice: - ArrayList lacks explicit push, pop, peek methods. - java.util.Stack or ArrayDeque is the idiomatic choice in Java. - This demo is educational to show structural similarity, not intended as robust design. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 267ed50 commit ff7d547

File tree

1 file changed

+4
-7
lines changed

1 file changed

+4
-7
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
package ListDemo.ArrayListLinkedListStack;
2-
31
import java.util.ArrayList;
42

5-
public class UseArrayListAsStack {
3+
public class ArrayListDemo5 {
64
public static void main(String[] args) {
5+
// Use Arraylist as a Stack.
76
ArrayList<Integer> ArrayLists = new ArrayList<>();
87
ArrayLists.add(1);
98
ArrayLists.add(2);
@@ -13,7 +12,5 @@ public static void main(String[] args) {
1312
ArrayLists.remove(ArrayLists.size()-1); //Pop
1413
}
1514
}
16-
/*
17-
arraylist as stack?
18-
Not good practice...In built methods are not available.
19-
*/
15+
16+
// arraylist as stack? Not good practice...In built methods they are not available.

0 commit comments

Comments
 (0)