🚀 ArrayDeque in Java 📌 How to use ArrayDeque ad = new ArrayDeque(); ad.add(10); ad.add(20); ad.add(30); System.out.println(ad); 📌 Points to Remember 1️⃣ Initial capacity = 16 2️⃣ Heterogeneous data → Yes, it will store 3️⃣ Preserves order of insertion 4️⃣ Duplicates are allowed 5️⃣ Null values are NOT allowed 📌 Constructors (3) 1. ArrayDeque() 2. ArrayDeque(int) 3. ArrayDeque(Collection) Example: LinkedList ll = new LinkedList(); ll.add(10); ll.add(20); ArrayDeque ad = new ArrayDeque(ll); 📌 Internal Structure 👉 Resizable array (Dynamic array) 📌 Hierarchy Iterable → Collection → Queue → Deque → ArrayDeque 📌 Accessing Elements ❌ No indexes in ArrayDeque ❌ Normal for loop will not work ✔️ Use for-each loop for(Object a : ad){ System.out.println(a); } 📌 Iterator (Forward) Iterator cursor = ad.iterator(); while(cursor.hasNext()){ System.out.println(cursor.next()); } 📌 Descending Iterator (Backward) Iterator cursor = ad.descendingIterator(); while(cursor.hasNext()){ System.out.println(cursor.next()); } 📌 When to use ArrayDeque ✔️ Heterogeneous data ✔️ Duplicate entries ✔️ No null values ✔️ Preserves order of insertion 🎯 Summary: ArrayDeque is a resizable array-based data structure that allows insertion and deletion from both ends, preserves order, allows duplicates, but does not allow null values and indexing. #Java #ArrayDeque #JavaCollections #Programming #Coding #Developers #Learning
Java ArrayDeque Overview and Usage
More Relevant Posts
-
🚀 Mastering ArrayDeque in Java — A Powerful Alternative to Stack & Queue If you're working with Java collections, one underrated yet powerful class you should know is ArrayDeque. It’s fast, flexible, and widely used in real-world applications. Here’s a crisp breakdown 👇 🔹 What is ArrayDeque? ArrayDeque is a resizable-array implementation of the Deque interface, which allows insertion and deletion from both ends. 💡 Key Features of ArrayDeque ✔️ Default initial capacity is 16 ✔️ Uses a Resizable Array as its internal data structure ✔️ Capacity grows using: CurrentCapacity × 2 ✔️ Maintains insertion order ✔️ Allows duplicate elements ✔️ Supports heterogeneous data ❌ Does NOT allow null values 🛠️ Constructors in ArrayDeque There are 3 types of constructors: 1️⃣ ArrayDeque() → Default capacity (16) 2️⃣ ArrayDeque(int numElements) → Custom initial capacity 3️⃣ ArrayDeque(Collection<? extends E> c) → Initialize with another collection 🔍 Accessing Elements Unlike Lists, ArrayDeque has some restrictions: ❌ Cannot use: Traditional for loop (index-based) ListIterator ✅ You can use: for-each loop Iterator Descending Iterator (for reverse traversal) 🧬 Hierarchy of ArrayDeque Iterable ↓ Collection ↓ Queue ↓ Deque ↓ ArrayDeque 👉 In simple terms: ArrayDeque implements Deque Deque extends Queue Queue extends Collection Collection extends Iterable 🔥 Why use ArrayDeque? ✔️ Faster than Stack (no synchronization overhead) ✔️ Efficient double-ended operations ✔️ Ideal for sliding window, palindrome checks, and BFS/DFS algorithms 💬 Final Thought If you're still using Stack, it might be time to switch to ArrayDeque for better performance and flexibility! #Java #DataStructures #ArrayDeque #Programming #JavaCollections #CodingInterview #SoftwareDevelopment TAP Academy
To view or add a comment, sign in
-
-
🗺️ 8 Java Maps. 8 Different Problems. Which One Do You Actually Need? Most developers default to HashMap for everything. That's like using a hammer for every job in the toolbox. 🔨 Here's the breakdown you didn't get in college: 1️⃣ HashMap → O(1) get/put, no ordering, not thread-safe ✅ Use when: you just need fast key-value lookup 2️⃣ LinkedHashMap → Maintains insertion order via doubly linked list ✅ Use when: building LRU caches or ordered iteration matters 3️⃣ TreeMap → Sorted keys, O(log n), backed by Red-Black tree ✅ Use when: you need range queries like subMap(), floorKey() 4️⃣ Hashtable → Synchronized, no nulls, legacy class ⚠️ Don't use it. Reach for ConcurrentHashMap instead. 5️⃣ ConcurrentHashMap → Thread-safe without locking the whole map ✅ Use when: multiple threads read/write simultaneously 6️⃣ WeakHashMap → Keys are weakly referenced — GC can collect them ✅ Use when: you need memory-sensitive caching (won't cause leaks) 7️⃣ EnumMap → Only enum keys, array-backed, blazing fast ✅ Use when: your keys are a fixed enum — state machines, configs 8️⃣ IdentityHashMap → Uses == instead of .equals() for key comparison ✅ Use when: object identity matters — serialization, graph traversal The rule is simple: Match the map to the problem, not the other way around. Choosing the wrong map is free today. The production bug it causes? Not so free. 🧨 💾 Save this before your next code review. ♻️ Repost if your team still uses Hashtable in 2026. 👇 Which map do you reach for most — and have you ever regretted it? #Java #SoftwareEngineering #Programming #BackendDevelopment #100DaysOfCode #CleanCode #JavaDeveloper #TechTwitter #CodingTips #DataStructures
To view or add a comment, sign in
-
-
8 Java Maps. 8 Different Problems. Which One Do You Actually Need? Most developers default to HashMap for everything. That's like using a hammer for every job in the toolbox. Here's the breakdown you didn't get in college: 1. HashMap → O(1) get/put, no ordering, not thread-safe. Use when: you just need fast key-value lookup. 2. LinkedHashMap → Maintains insertion order via doubly linked list. Use when: building LRU caches or ordered iteration matters. 3. TreeMap → Sorted keys, O(log n), backed by Red-Black tree. Use when: you need range queries like subMap(), floorKey(). 4. Hashtable → Synchronized, no nulls, legacy class. Don't use it. Reach for ConcurrentHashMap instead. 5. ConcurrentHashMap → Thread-safe without locking the whole map. Use when: multiple threads read/write simultaneously. 6. WeakHashMap → Keys are weakly referenced — GC can collect them. Use when: you need memory-sensitive caching (won't cause leaks). 7. EnumMap → Only enum keys, array-backed, blazing fast. Use when: your keys are a fixed enum — state machines, configs. 8. IdentityHashMap → Uses == instead of .equals() for key comparison. Use when: object identity matters — serialization, graph traversal. The rule is simple: Match the map to the problem, not the other way around. Choosing the wrong map is free today. The production bug it causes? Not so free. Save this before your next code review. Repost if your team still uses Hashtable in 2026. Which map do you reach for most — and have you ever regretted it? #Java #SoftwareEngineering #Programming #BackendDevelopment #100DaysOfCode #CleanCode #JavaDeveloper #TechTwitter #CodingTips #DataStructures
To view or add a comment, sign in
-
-
💻 String vs StringBuffer vs StringBuilder in Java – Know the Difference! In Java, handling text data is very common. Let’s understand the three important classes: 🔹 1. String ✔ Immutable (cannot be changed once created) ✔ Any modification creates a new object ✔ Safe and widely used Example: "String s = "Hello";" "s = s + " World"; // creates new object" --- 🔹 2. StringBuffer ✔ Mutable (can be changed) ✔ Thread-safe (synchronized) ✔ Slightly slower due to synchronization Example: "StringBuffer sb = new StringBuffer("Hello");" "sb.append(" World");" --- 🔹 3. StringBuilder ✔ Mutable (can be changed) ✔ Not thread-safe ✔ Faster than StringBuffer Example: "StringBuilder sb = new StringBuilder("Hello");" "sb.append(" World");" --- 💡 Key Difference: String = Immutable StringBuffer = Mutable + Thread-safe StringBuilder = Mutable + Faster 🚀 Use String for simple tasks, StringBuffer for multi-threading, and StringBuilder for better performance in single-threaded applications. #FortuneCloudTechnology #Java #Programming #String #JavaBasics #Coding #Developers #Learning
To view or add a comment, sign in
-
💡 Java Collections (Revision)— What to Use, When, and What's Happening Internally Most developers use collections daily. Very few understand what's happening under the hood. Here's a clean breakdown 👇 🔹 LIST — Ordered, Allows Duplicates ArrayList ✔ Backed by dynamic array ✔ Fast random access O(1) ✔ Use when: frequent reads, less modification LinkedList ✔ Doubly linked list ✔ Fast insert/delete O(1) ✔ Use when: frequent insertions/deletions 🔹 SET — Unique Elements HashSet ✔ Uses HashMap internally ✔ No order, O(1) operations ✔ Use when: fast lookup, uniqueness LinkedHashSet ✔ HashSet + insertion order ✔ Uses LinkedHashMap internally ✔ Use when: need order + uniqueness TreeSet ✔ Red-Black Tree, sorted order, O(log n) ✔ Use when: sorted data required 🔹 MAP — Key-Value Pairs HashMap ✔ Bucket array + hashing ✔ Linked list → Tree (Java 8+), O(1) avg ✔ Use when: fast key-value access LinkedHashMap ✔ HashMap + doubly linked list ✔ Maintains insertion order ✔ Use when: LRU cache / predictable iteration TreeMap ✔ Red-Black Tree, sorted keys ✔ Use when: sorted map needed ConcurrentHashMap ✔ Thread-safe, CAS + bucket-level locking ✔ Lock-free reads ✔ Use when: multi-threaded systems 🔥 Internal Patterns You Should Know ✔ Hashing converts key to bucket index ✔ Collisions resolved via Linked List then Tree ✔ CAS enables lock-free updates in ConcurrentHashMap ✔ Red-Black Tree keeps operations at O(log n) ✔ Doubly Linked List maintains insertion order ⚠️ Common Mistakes ✔ Using LinkedList for random access ✔ Bad hashCode() causing performance issues ✔ Using HashMap in multithreaded code ✔ Ignoring ordering requirements 🧠 One Line Memory Trick l List → Order + Duplicates Set → No duplicates Map → Key → Value Mastering collections = mastering backend performance. #Java #Collections #DataStructures #SoftwareEngineering #BackendDevelopment #SystemDesign
To view or add a comment, sign in
-
-
Java and JavaScript are not call by reference. It's time to clarify a common myth: “Java / JavaScript pass objects by reference” is not true. Both languages strictly use call by value, similar to Python. Why the confusion? When you pass objects, changes can sometimes reflect outside the function, which may appear to be call by reference. However, it’s actually value copying. To understand this, consider the memory architecture: - Stack: Stores variables and function calls, with each call creating a new stack frame. - Heap: Stores actual objects. Here’s what happens during a function call: 1. Variable Creation: - Primitives store actual values. - Objects store references (memory addresses). 2. Function / Method Call: - A new stack frame is created, and parameters become new local variables. 3. Core Step — Value Copy: - The value of the argument is copied. For primitives, the data is copied; for objects, the reference (address) is copied. It’s still a copy in both cases. 4. Inside Function: - Mutation works (e.g., 'obj.name = "Ishwar"' changes the same object in the heap). - Reassignment does not work (e.g., 'obj = new Object()' only changes the local copy). 5. Function Ends: - The stack frame is destroyed, and original variables remain unchanged. Mental Model: The caller variable copies the value to the function parameter, providing no direct access to the original variable—only a copy is used. This behavior applies to multiple languages: - Java: Call by value - JavaScript: Call by value - Python: Call by value (object reference) - C#: Call by value (default) Final truth: “Everything is pass by value. Some values just happen to be references.” 🔖 Follow CodeWithIshwar for more deep dives into real-world programming concepts. #CodeWithIshwar #Java #JavaScript #Python #Programming #SoftwareEngineering #BackendDevelopment #Coding #Developers #Tech #ComputerScience #OOP #Debugging
To view or add a comment, sign in
-
🔥 Day 18: Serialization & Deserialization (Java) A very important concept for saving and transferring objects in Java 👇 🔹 1. Serialization 👉 Definition: Converting an object into a byte stream so it can be saved to a file or sent over a network. ✔ Used for file storage 📁 ✔ Used in networking 🌐 ✔ Implemented using Serializable interface 🔹 2. Deserialization 👉 Definition: Converting the byte stream back into an object. ✔ Restores object state ✔ Used when reading from file/network 🔹 Simple Example import java.io.*; // Serializable class class Student implements Serializable { int id; String name; Student(int id, String name) { this.id = id; this.name = name; } } public class Main { public static void main(String[] args) throws Exception { // Serialization Student s1 = new Student(1, "Java"); ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("data.txt")); oos.writeObject(s1); oos.close(); // Deserialization ObjectInputStream ois = new ObjectInputStream( new FileInputStream("data.txt")); Student s2 = (Student) ois.readObject(); ois.close(); System.out.println(s2.id + " " + s2.name); } } 🔹 Key Points ✔ Must implement Serializable interface ✔ Use ObjectOutputStream → write object ✔ Use ObjectInputStream → read object ✔ transient keyword → skip fields 🔹 Real-Life Analogy 📦 Serialization = Packing an object into a box 📦 Deserialization = Unpacking it back 💡 Pro Tip: Always define serialVersionUID to avoid version mismatch issues 📌 Final Thought: "Serialization turns objects into data, Deserialization brings them back to life." #Java #Serialization #Deserialization #Programming #JavaDeveloper #Coding #InterviewPrep #Day18
To view or add a comment, sign in
-
-
Java Devs, let's talk about a core concept that makes our code cleaner and more flexible: "Method Overloading"! Ever wanted to perform similar operations with different inputs without creating a bunch of uniquely named methods? That's where Method Overloading shines! It's a fantastic example of compile-time polymorphism (aka static polymorphism or early binding) that allows a class to have multiple methods with the "same name", as long as their parameter lists are different. Key takeaways: * Same method name, different parameters = ✅ * Cannot overload by return type alone (parameters *must* differ) ⚠️ * The compiler is smart! It picks the most specific match. 🧠 Check out this quick example: ```java class Product { public int multiply(int a, int b) { // Multiplies two numbers return a * b; } public int multiply(int a, int b, int c) { // Multiplies three numbers return a * b * c; } } // Output: // Product of the two integer value: 2 // Product of the three integer value: 6 ``` See how elegant that is? One `multiply` method, multiple functionalities! What are your favorite use cases for Method Overloading in your Java projects? Share in the comments! 👇 #Java #JavaDevelopment #Programming #SoftwareDevelopment #BeginnerProgramming
To view or add a comment, sign in
-
-
🚀 Java Trap: Why "finally" Doesn’t Change the Returned Value 👇 👉 Primitive vs Object Behavior in "finally" 🤔 Looks tricky… but very important to understand. --- 👉 Example 1 (Primitive): public static int test() { int x = 10; try { return x; } finally { x = 20; } } 👉 Output: 10 😲 Why not 20? 💡 Java stores return value before executing "finally" - "x = 10" stored - "finally" runs → changes "x" to 20 - But already stored value (10) is returned --- 👉 Example 2 (Object): public static StringBuilder test() { StringBuilder sb = new StringBuilder("Hello"); try { return sb; } finally { sb.append(" World"); } } 👉 Output: Hello World 😲 Why changed here? 💡 Object reference is returned - Same object is modified in "finally" - So changes are visible --- 🔥 Rule to remember: - Primitive → value copied → no change - Object → reference returned → changes visible --- 💭 Subtle concept… very common interview question. #Java #Programming #Coding #Developers #JavaTips #InterviewPrep 🚀
To view or add a comment, sign in
-
⚡ Few powerful Java methods every developer should know Some Java methods look small… but they unlock powerful behavior under the hood. Here are a few that are worth understanding 👇 🔹 Class.forName() Loads a class dynamically at runtime 👉 Commonly used when the class name is not known at compile time (e.g., drivers, plugins) 🔹 Thread.yield() Hints the scheduler to pause the current thread 👉 Gives other threads a chance to execute (not guaranteed, just a suggestion) 🔹 String.intern() Moves a String to the String Pool (if not already present) 👉 Helps save memory by reusing identical string values 🔹 map.entrySet() Returns a set of key-value pairs from a Map 👉 Most efficient way to iterate both key and value together 🔹 Object.wait() Makes a thread wait until another thread notifies it 👉 Used for inter-thread communication (must be inside synchronized block) 🔹 Thread.join() Pauses current thread until another thread finishes 👉 Useful when execution order matters 🔹 stream().flatMap() Flattens nested data structures into a single stream 👉 Perfect for transforming lists of lists into a single list 💡 Why these matter? These methods touch core areas of Java: • Concurrency • Memory optimization • Collections • Functional programming Understanding them helps you write cleaner, more efficient code. 📌 Which one do you use most often? #Java #Programming #SoftwareDevelopment #Coding #BackendDevelopment #Tech
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