Commit ff7d547
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- Section 25 Collections Frameworks/List Interface/ArrayList/src
1 file changed
+4
-7
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | 1 | | |
4 | 2 | | |
5 | | - | |
| 3 | + | |
6 | 4 | | |
| 5 | + | |
7 | 6 | | |
8 | 7 | | |
9 | 8 | | |
| |||
13 | 12 | | |
14 | 13 | | |
15 | 14 | | |
16 | | - | |
17 | | - | |
18 | | - | |
19 | | - | |
| 15 | + | |
| 16 | + | |
0 commit comments