Day 63 of Sharing What I’ve Learned 🚀 Two-Way Traversal in Java — Going Forward and Backward with ListIterator After understanding how Iterator helps traverse collections safely, I explored something even more powerful — traversing a list in both directions. And that is where ListIterator comes in. Unlike Iterator, which moves only forward, ListIterator gives us the flexibility to: move forward move backward add elements update elements remove elements safely That makes it especially useful when working with List implementations like ArrayList and LinkedList. 🔹Why it matters Sometimes, data is not just meant to be read from top to bottom. In real applications, we may need to: revisit previous elements make changes while traversing move in both directions without restarting the loop That is exactly what makes ListIterator so useful. 🔹Key methods hasNext() → checks if next element exists next() → moves forward hasPrevious() → checks if previous element exists previous() → moves backward add() → inserts element set() → updates current element remove() → deletes element safely 🔹Simple example import java.util.*; public class Main { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("C++"); ListIterator<String> it = list.listIterator(); System.out.println("Forward traversal:"); while (it.hasNext()) { System.out.println(it.next()); } System.out.println("Backward traversal:"); while (it.hasPrevious()) { System.out.println(it.previous()); } } } 🔹My realization Iterator taught me how to traverse safely. ListIterator taught me how to traverse smartly. 👉 Forward only is useful 👉 Forward + backward gives more control 👉 More control means more flexibility in programming Today I understood that Java collections are not just about storing data — they are also about navigating it in the right way. #Java #Collections #ListIterator #Iterator #Programming #DataStructures #100DaysOfCode #DeveloperJourney #Day63 Grateful for guidance from TAP Academy Sharath R kshitij kenganavar
Java ListIterator for Forward and Backward Traversal
More Relevant Posts
-
Day 47 TAP Academy | Mastering Java LinkedList Today’s learning unlocked one of Java’s most dynamic data structures — the LinkedList. Here’s a crisp breakdown of what I explored and refined 👇 🔹 What is LinkedList? LinkedList in Java is a class that implements a doubly linked list structure. Unlike arrays, elements are stored in nodes connected via references (previous + next). 🔹 Key Properties: ✔ No fixed capacity — grows dynamically as elements are added ✔ Allows duplicate values ✔ Supports null elements ✔ Maintains insertion order ✔ Efficient memory usage for frequent insert/delete operations 🔹 Constructors: • LinkedList() → creates an empty list • LinkedList(Collection c) → allows easy conversion from other collections like ArrayList 🔹 Internal Working: Each node contains: • Data • Reference to previous node • Reference to next node This structure enables smooth insertion and deletion without shifting elements. 🔹 Hierarchy: LinkedList → Extends AbstractSequentialList → Implements List, Deque This makes it powerful enough to act as: ✔ List ✔ Queue ✔ Deque 🔹 Ways to Access Elements: 1. For loop (index-based) 2. Enhanced for-loop 3. Iterator (forward traversal) 4. ListIterator (bi-directional traversal) 🔹 LinkedList vs ArrayList: 📌 ArrayList • Fast access (O(1)) • Slow insert/delete in middle (O(n)) 📌 LinkedList • Fast insert/delete (O(1) at known position) • Slower access (O(n)) due to traversal 🔹 When to Use LinkedList? ✔ Frequent insertions/deletions ✔ Working with queues, stacks, or deques ✔ When shifting elements is costly 🔹 Key Insight: Java handles all node management internally — no need for manual pointer handling like in C. This makes development faster and safer. Another solid step forward in mastering Java Collections 💡 kshitij kenganavar Sharath R Harshit T Ravi Magadum Sonu Kumar Dinesh K Ayush Tiwari Ravikant Agnihotri MIDHUN M Hari Krishnan R.S #Day47 #TapAcademy #Java #JavaDeveloper #LinkedList #DataStructures #Programming #CodingJourney #LearnToCode #SoftwareEngineering #JavaCollections #DSA #CodingLife #Developers #TechLearning #100DaysOfCode #CodeNewbie #BackendDevelopment #ProgrammingLife #TechSkills #ComputerScience #CodingCommunity #GrowthMindset #FutureEngineer
To view or add a comment, sign in
-
-
🚀 Day 47 of My Learning Journey – Java Wrapper Classes Today, I explored Wrapper Classes in Java, an important concept that bridges primitive data types and objects. 🔍 What I Learned: ✔️ Wrapper classes convert primitive data types into objects ✔️ Each primitive type has a corresponding wrapper class (e.g., int → Integer, char → Character, double → Double) ✔️ Enables use of primitives in collections like ArrayList 💡 Key Concepts: 🔹 Autoboxing – Automatic conversion of primitive to object 🔹 Unboxing – Converting object back to primitive 🔹 Useful methods like parseInt(), toString(), and valueOf() 📊 Why It Matters: Wrapper classes make Java more flexible by allowing primitives to be treated as objects, especially when working with frameworks and collections. 📌 Example Use Case: Storing integers in an ArrayList using Integer instead of int. 🎯 Takeaway: Understanding wrapper classes is essential for writing efficient and modern Java programs. #Java #LearningJourney #Programming #Day47 #TechSkills #Developers #Coding
To view or add a comment, sign in
-
-
Day 53 of Sharing What I’ve Learned 🚀 ArrayDeque in Java — Fast & Flexible Queue Alternative After understanding how LinkedList works as a Queue, I explored a more optimized and powerful structure in the Java Collections Framework — ArrayDeque 🔹 What is ArrayDeque? ArrayDeque is a resizable array-based implementation of a Deque (Double-Ended Queue). 👉 It allows insertion and deletion from both ends efficiently. 🔹 Why use ArrayDeque over LinkedList? ✔ Faster Performance No node traversal → better speed compared to LinkedList. ✔ No Extra Memory Overhead Doesn’t store pointers like LinkedList → more memory efficient. ✔ Better Cache Performance Elements are stored contiguously → faster access. ✔ Acts as Stack + Queue Can be used as: Stack (LIFO) Queue (FIFO) Deque (both ends) 🔹 Key Operations ✔ addFirst() / addLast() ✔ removeFirst() / removeLast() ✔ peekFirst() / peekLast() 🔹 When should we use ArrayDeque? 👉 Use ArrayDeque when: ✔ You need fast insertions/deletions at both ends ✔ You want a better alternative to Stack or LinkedList ✔ Performance matters (less overhead) 🔹 When NOT to use? ❌ When you need random access (indexing) ❌ When frequent middle operations are required 🔹 Key Insight 💡 Not all Queues are equal — 👉 Choosing the right implementation (LinkedList vs ArrayDeque) can significantly impact performance. 🔹 Day 53 Realization 🎯 Efficiency isn’t just about solving problems — 👉 It’s about solving them smartly with the right tools. #Java #ArrayDeque #DataStructures #CollectionsFramework #Programming #DeveloperJourney #100DaysOfCode #Day53 Grateful for guidance from, Sharath R TAP Academy
To view or add a comment, sign in
-
-
🚀 Day 44 of My Learning Journey Today I explored some important concepts in Java related to memory management and threading. Here’s what I learned: 🔹 Finalize Method Used before an object is garbage collected. Helps in performing cleanup activities like closing resources. However, it's not reliable and is now considered outdated in modern Java practices. 🔹 Mark and Sweep Algorithm A key technique used in Garbage Collection. Mark Phase: Identifies objects that are still in use. Sweep Phase: Removes unused objects from memory. Improves memory efficiency and prevents memory leaks. 🔹 Garbage Collector Automatically manages memory by removing unused objects. Helps developers focus more on logic rather than memory handling. Works in the background for better performance. 🔹 Daemon Thread A low-priority thread that runs in the background. Supports main threads (e.g., garbage collection). Automatically stops when all user threads finish execution. 💡 Key Takeaway: Understanding how memory is managed and how background threads work is crucial for writing efficient and optimized Java programs. #Java #GarbageCollection #Multithreading #LearningJourney #Programming #Developer
To view or add a comment, sign in
-
-
🚀 Mastering Java Collections – Array vs ArrayList vs LinkedList vs ArrayDeque As part of my Java learning journey at Tap Academy, I explored the core differences between Array, ArrayList, LinkedList, and ArrayDeque. Understanding when to use each is crucial for writing efficient and optimized code. 🔹 1. Array Fixed size (defined at creation) Supports primitive + object types Stored in continuous memory Fast access → O(1) No built-in methods (limited operations) Cannot resize dynamically Allows duplicates & null Can be multi-dimensional 👉 Best when: Size is fixed Performance is critical Working with primitive data 🔹 2. ArrayList Dynamic (resizable array) Default capacity → 10 Allows duplicates, null, heterogeneous data Maintains insertion order Fast access → O(1) Insertion (middle) → O(n) (shifting) Rich built-in methods Stored in continuous memory 👉 Best when: Frequent data access/searching Need dynamic resizing Need utility methods 🔹 3. LinkedList Doubly linked list structure Dynamic size Allows duplicates, null, heterogeneous data Maintains insertion order Insertion/deletion → O(1) Access → O(n) (traversal) Uses dispersed memory (nodes) Implements List + Deque 👉 Best when: Frequent insertions/deletions Queue/Deque/Stack operations 🔹 4. ArrayDeque Resizable circular array Default capacity → 16 Allows duplicates & heterogeneous data ❌ Does not allow null No index-based access Fast insertion/deletion → O(1) Faster than Stack & LinkedList for queue operations Implements Deque 👉 Best when: Need fast operations at both ends Implementing stack/queue efficiently 🔥 Key Takeaway 👉 Use the right structure based on use case: Array → Fixed size + performance ArrayList → Fast access LinkedList → Frequent modifications ArrayDeque → Best for queue/stack operations Choosing the right data structure directly impacts performance, memory, and scalability. Grateful to Tap Academy for building strong fundamentals in Java Collections 🚀 🙌 Special thanks to the amazing trainers at TAP Academy: kshitij kenganavar Sharath R MD SADIQUE Bibek Singh Hemanth Reddy Vamsi yadav Harshit T Ravi Magadum Somanna M G Rohit Ravinder TAP Academy #TapAcademy #Week13Learning #CoreJava #CollectionsFramework #ArrayList #LinkedList #ArrayDeque #DataStructures #JavaFundamentals #LearningByDoing #FullStackJourney #VamsiLearns
To view or add a comment, sign in
-
-
Day 45 at TAP Academy | ArrayList in Java Today’s session was all about unlocking the power of ArrayList — one of Java’s most flexible and widely used data structures. From dynamic resizing to efficient data handling, this topic felt like upgrading from a static storage box to a smart, expandable warehouse. 🔹 ArrayList Fundamentals • ArrayList is a built-in class in Java used to store dynamic collections of data. • Objects are stored in the heap memory. • Default initial capacity is 10. • It extends AbstractList and implements List, Collection, Iterable. • Allows: - Heterogeneous data - Duplicate elements - Null values - Maintains insertion order 🔹 Constructors • ArrayList() • ArrayList(int capacity) • ArrayList(Collection c) 🔹 Essential Methods • add(data) → adds element at the end • add(index, data) → inserts at a specific position • set(index, data) → updates element at index • get(index) → retrieves element • size() → returns number of elements • addAll(Collection) → merges collections • retainAll(Collection) → keeps common elements • removeAll(Collection) → removes matching elements • trimToSize() → optimizes memory usage • contains(data) → checks presence • subList(from, to) → extracts a portion • clear() → removes all elements 🔹 Performance Insights • Insertion at end (no resize) → O(1) • Insertion with resizing → O(n) • Growth formula → (current capacity × 3/2) + 1 • Efficient usage improves scalability and performance 🔹 Traversal Techniques • for loop • for-each loop • Iterator (forward only) • ListIterator (forward + backward) Understanding ArrayList is like learning how data breathes inside applications — dynamic, adaptive, and efficient. This foundation is crucial for writing optimized and scalable Java programs. kshitij kenganavar Sharath R Harshit T Ravi Magadum Sonu Kumar Dinesh K MIDHUN M Hari Krishnan R.S Ayush Tiwari Ravikant Agnihotri #Java #ArrayList #DataStructures #Programming #Coding #Developer #SoftwareEngineering #JavaDeveloper #LearnJava #CodingJourney #TechSkills #ComputerScience #100DaysOfCode #DevelopersLife #ProgrammingLife #CodeNewbie #TechEducation #FutureDevelopers #CodingSkills #JavaCollections #BackendDevelopment #ProgrammingConcepts #CodeDaily #GrowthMindset #TechCareer #LearningJourney #TapAcademy #Day45 #Consistency #KeepLearning #BuildInPublic #SoftwareDeveloper #EngineeringLife #CodeBetter
To view or add a comment, sign in
-
-
🚀 Day-49 @ Tap Academy | Mastering ArrayDeque & TreeSet in Java Today’s learning was all about understanding two powerful components of the Java Collection Framework: ArrayDeque and TreeSet — both designed to solve different real-world problems efficiently. 🔹 ArrayDeque (Double-Ended Queue) ArrayDeque is a resizable array implementation of the Deque interface, which allows insertion and deletion from both ends. 👉 Key Features: Faster than Stack and LinkedList for queue operations No capacity restrictions (dynamic resizing) Does not allow null elements Can be used as both Stack (LIFO) and Queue (FIFO) 👉 Common Methods: addFirst(), addLast() removeFirst(), removeLast() peekFirst(), peekLast() 👉 Use Case: Efficient for scenarios like task scheduling, undo operations, or sliding window problems. 🔹 TreeSet (Sorted Set Implementation) TreeSet is a part of the SortedSet interface and is backed by a Red-Black Tree. 👉 Key Features: Stores unique elements only Maintains natural sorting order (ascending by default) Does not allow null elements Provides log(n) time complexity for basic operations 👉 Common Methods: add(), remove() first(), last() higher(), lower() 👉 Use Case: Ideal when you need sorted data without duplicates, like ranking systems or leaderboards. 💡 Key Difference: ArrayDeque → Focuses on fast insertion/removal from both ends TreeSet → Focuses on sorted, unique data storage ✨ Learning these concepts strengthens my understanding of how to choose the right data structure for optimized performance. 📌 What’s your go-to collection in Java for performance-critical applications? #Day49 #JavaLearning #TapAcademy #DataStructures #JavaCollections #CodingJourney #SoftwareDevelopment #LearningInPublic #Developers #Programming #TechCareers
To view or add a comment, sign in
-
-
🚀 Day 3 of My Coding Challenge Improving my problem-solving skills step by step! Today I solved a number-based problem on reversing an integer. 🔹 Platforms: LeetCode & GeeksforGeeks 🔹 Problem: LeetCode #7 – Reverse Integer 🔹 Problem Statement: Given a signed 32-bit integer, reverse its digits. If the reversed integer overflows, return 0. 🔹 Approach: 1️⃣ Extract last digit using modulo (%) 2️⃣ Build reversed number step by step 3️⃣ Check for overflow before updating result 🔹 Example: Input: 123 → Output: 321 Input: -123 → Output: -321 Input: 120 → Output: 21 🔹 What I learned: ✔ Handling integer overflow conditions ✔ Working with digits using modulo & division ✔ Writing safe and optimized code 💻 Code: import java.util.*; public class ReverseIntegerLeetCode7 { ``` public static int reverse(int x) { int rev = 0; while (x != 0) { int rem = x % 10; x = x / 10; // Check overflow if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && rem > 7)) { return 0; } if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && rem < -8)) { return 0; } rev = (rev * 10) + rem; } return rev; } public static void main(String[] args) { int x = 123; System.out.println(reverse(x)); x = -123; System.out.println(reverse(x)); x = 120; System.out.println(reverse(x)); } ``` } 🔗 GitHub: https://lnkd.in/g-wNSrPq #Java #DSA #LeetCode #CodingChallenge #50DaysChallenge #Consistency #GrowthMindset #LearningJourney
To view or add a comment, sign in
-
🚀 Day 1 of My Coding Challenge Today I solved an interesting problem on Array Rotation using Java. 🔹 Problem: Rotate an array to the left by ‘d’ positions efficiently. 🔹 Approach: Instead of shifting elements one by one, I used the Reversal Algorithm: 1️⃣ Reverse first d elements 2️⃣ Reverse remaining elements 3️⃣ Reverse entire array 🔹 Example: Input: [1, 2, 3, 4, 5], d = 2 Output: [3, 4, 5, 1, 2] 🔹 What I learned: ✔ Optimized solution from O(n*d) → O(n) ✔ Importance of breaking problems into smaller steps ✔ In-place array manipulation 💻 Code: ```java import java.util.Arrays; class Solution { public static int[] reverse(int[] arr, int start, int end) { while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } return arr; } static int[] rotateArr(int arr[], int d) { int n = arr.length; d = d % n; if (d < 0) { d = d + n; } reverse(arr, 0, d - 1); reverse(arr, d, n - 1); reverse(arr, 0, n - 1); return arr; } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int d = 2; int[] res = rotateArr(arr, d); System.out.println(Arrays.toString(res)); } } ``` #Java #DSA #CodingChallenge #50DaysOfCode #LearningJourney #PlacementPreparation
To view or add a comment, sign in
-
Day 62 of Sharing What I’ve Learned🚀 Iterator in Java — Safe and Efficient Traversal After understanding how collections store and organize data, I revisited an important concept — how to safely traverse them using Iterator. 👉 Accessing data is easy… but doing it correctly and safely matters more. 🔹 What is an Iterator? Iterator is an interface in Java used to traverse elements of a collection one by one. 👉 It provides a standard way to loop through: ArrayList HashSet LinkedList And more… 🔹 Why not just use a for loop? Using a normal loop works… but it has limitations: ❌ Not safe when modifying collection ❌ Can lead to ConcurrentModificationException ❌ Not universal for all collection types 👉 That’s where Iterator comes in ✔ 🔹 Key Methods of Iterator hasNext() → checks if next element exists next() → returns the next element remove() → removes the current element safely 🔹 Example import java.util.*; public class Main { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("C++"); Iterator<String> it = list.iterator(); while(it.hasNext()) { String lang = it.next(); System.out.println(lang); } } } 🔹 Real Advantage 💡 👉 Removing elements while iterating: Iterator<String> it = list.iterator(); while(it.hasNext()) { if(it.next().equals("Python")) { it.remove(); // Safe removal } } ✔ No errors ✔ Clean logic ✔ Interview-friendly concept 🔹 Day 62 Realization Traversing data is not just about loops — it’s about doing it safely and efficiently. 👉 Iterator provides better control and prevents runtime issues 👉 Essential when working with dynamic collections #Java #Collections #DataStructures #CollectionsFramework #Iterator #Programming #DeveloperJourney #100DaysOfCode #Day61 Grateful for guidance from, TAP Academy Sharath R kshitij kenganavar
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development