I build my own Stack data structure in Java (Array + LinkedList implementation) I did'nt just added simple (push/pop) operations, i actually implemented some decent methods in both implementations. I overrode the toString() method so that whenever the object reference is printed, it displays the stack’s contents instead of the default memory address representation. When building using Array the most important concept i learned is dynamic resizing. 🔹 Array-based Dynamic Stack: Generic implementation (Stack<T>) Dynamic resizing (capacity doubles when full) push, pop, peek, search trimToSize() for memory optimization reverse() using two-pointer technique swapTop() utility method clone() for deep copy pushAll() with varargs & collections popMultiple() for batch operations 🔹 Linked List-based Stack Generic stack with Comparable support Efficient push / pop using head pointer contains() search operation toArray() conversion clone() while preserving order sort() functionality using Collections.sort() Batch operations like pushAll() and pop(k) 💡 Key concepts practiced Generics in Java Dynamic memory management Custom exception handling Linked list node design Time complexity considerations (O(1) push/pop) Designing reusable APIs This exercise helped me understand how real data structures work internally, instead of just using library implementations. View comment section for the code on github. Next, I'm planning to implement: Queue (Array + Linked List) Deque Iterator support for custom data structures Always open to feedback, suggestions, or improvements from experienced developers. #Java #DataStructures #DSA #ComputerScience #SoftwareEngineering #LearningInPublic #JavaDeveloper
More Relevant Posts
-
💡 How do threads actually “talk” to each other in Java? Not by magic… but using wait() and notify() 👇 ⸻ One of the most common (and important) multithreading problems is the Producer-Consumer problem. 🧠 The idea: • Producer thread → generates data • Consumer thread → consumes data • Both share the same resource But coordination is the real challenge ⚠️ 👉 What if the Producer produces when data already exists? 👉 What if the Consumer tries to consume before data is available? ⸻ ⚙️ Here’s how Java solves it using synchronized, wait() & notify() class SharedResource { private int data; private boolean hasData = false; public synchronized void produce(int value) throws InterruptedException { while (hasData) { wait(); // wait if data already exists } data = value; System.out.println("Produced: " + data); hasData = true; notify(); // wake up consumer } public synchronized void consume() throws InterruptedException { while (!hasData) { wait(); // wait if no data } System.out.println("Consumed: " + data); hasData = false; notify(); // wake up producer } } 🚀 What’s really happening here? • wait() → pauses the thread & releases the lock 🔓 • notify() → wakes up another waiting thread 🔔 • synchronized → ensures only one thread accesses at a time ⸻ ⚠️ Golden Rules: ✔ Always use wait() inside a while loop (not if) ✔ Must call wait() / notify() inside synchronized blocks ✔ Threads re-acquire the lock after waking up ⸻ 🔥 Why this matters: This pattern is used in: • Task queues • Messaging systems • Real-time data pipelines ⸻ 💬 Multithreading isn’t just about running multiple threads… It’s about making them work in perfect sync. ⸻ #Java #Multithreading #ProducerConsumer #Concurrency #BackendDevelopment #CodingInterview
To view or add a comment, sign in
-
-
🔹 In Java, the Map hierarchy forms the foundation for key-value data structures: Map interface → HashMap, LinkedHashMap, TreeMap. Each has its own behavior and use-case in terms of ordering, and sorting. Many developers use HashMap daily, but do you know what happens behind the scenes? Let’s decode it 👇 HashMap Internals: Beyond Simple Key-Value Storage 1️⃣ Buckets & Nodes HashMap stores entries in an array of buckets. Each bucket contains nodes, and each node holds a key-value pair. 2️⃣ Hashing: The Core Mechanism Every key generates a hash code, which is used to compute the bucket index: index = (n - 1) & hash This ensures efficient data distribution and fast access. 3️⃣ Collision Handling When multiple keys map to the same bucket → collision occurs. Java handles collisions using: Linked List (Java < 8) Red-Black Tree (Java 8+, when bucket size > 8) 4️⃣ Insertion & Retrieval Insertion (put): hash → bucket → insert/update node Retrieval (get): hash → bucket → traverse nodes → match key 5️⃣ Resize & Load Factor Default capacity = 16, load factor = 0.75 When size > capacity × load factor, HashMap resizes (doubles capacity) to maintain performance 💡 Performance Insights Average case: O(1) ✅ Worst case: O(log n) after Java 8 ✅ Takeaway: A well-implemented hashCode() and equals() is key to fast, reliable HashMap performance. #Java #HashMap #DataStructures #Programming #SoftwareEngineering #CodingTips #DeveloperInsights
To view or add a comment, sign in
-
-
🚀 From Temporary Memory to Persistent Data — My Deep Dive into Java File Handling While studying Java File Handling, I realized an important concept about how programs manage data. When a program runs, data is stored in RAM (temporary memory). But once the program stops, that data disappears. So the real challenge is: How do applications preserve data even after the program stops running? This is where File Handling becomes essential. It allows programs to store data on disk (files) so it can be read again later. 📂 File Class Java provides the File class to interact with the file system. Operations I explored: • createNewFile() → create a file • mkdir() / mkdirs() → create directories • exists() → check file existence • list() → list files inside a directory Important: The File class manages files, but it does not read or write data. 📦 Streams — Reading & Writing Data Actual data operations are done using Streams. File → Program → Input Stream (Read) Program → File → Output Stream (Write) Examples: FileInputStream FileOutputStream Streams process data byte by byte, allowing efficient file handling. ⚡ Buffered Streams To improve performance, Java uses Buffered Streams. A buffer temporarily stores data before transferring it. Program → Buffer → File Examples: BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter This significantly improves I/O performance. 🔐 Serialization & Deserialization Serialization converts a Java object into a byte stream so it can be stored or transmitted. Key concepts: Serializable interface serialVersionUID transient keyword ObjectOutputStream The reverse process, Deserialization, converts the byte stream back into the original object using ObjectInputStream. 💡 Key Insight Java File Handling connects multiple core concepts: • RAM vs Disk storage • Data persistence • Stream-based data flow • Buffered I/O optimization • Object serialization & deserialization Understanding this helped me see how Java applications store, manage, and retrieve data in real systems. Grateful to my mentor Prasoon Bidua at REGex Software Services for guiding us to understand the “why behind the technology.” #Java #JavaDeveloper #FileHandling #Serialization #JavaIO #BackendDevelopment
To view or add a comment, sign in
-
-
🔥 Understanding data structures in Java: Linked Lists explained! 🚀 Linked lists are a fundamental data structure where each element (node) is linked to the next one in line. They are flexible and dynamic, allowing for efficient insertions and deletions. Developers use linked lists to manage and organize data in an orderly manner, crucial for optimizing memory usage and improving performance. Ready to dive in? Here's a step-by-step breakdown: 1. Create a Node class to represent the elements. 2. Implement methods for insertion, deletion, and traversal. 3. Manage the connections between nodes correctly. Full code example: ```java class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } } ``` Pro tip: Always ensure to update the pointers carefully when manipulating linked lists to avoid errors. Common mistake to avoid: Forgetting to update the pointer references when adding or removing nodes can lead to memory leaks. 🌟 What other data structures have you explored in Java? Share your favorites! 💬 🌐 View my full portfolio and more dev resources at tharindunipun.lk #DataStructures #JavaProgramming #LinkedLists #CodingTips #DeveloperCommunity #MemoryManagement #PerformanceOptimization #TechExplained
To view or add a comment, sign in
-
-
I created a small #Java library (with zero dependency) to extract #JSON structures from chatty #LLM outputs that don't always output pure JSON. Then you pass that extracted JSON content to a tolerant parser like #Jackson in case the LLM decided to add comments, to unquote keys or what not! https://lnkd.in/emi_PsR4
To view or add a comment, sign in
-
Peglib 0.2.0 + 0.2.1 -- Major code generation reliability release Peglib is a PEG parser library for Java, inspired by cpp-peglib. It lets you define parsers using PEG grammar syntax, with support for both runtime interpretation and standalone source code generation. These two releases focused on one goal: making the generated standalone parser produce identical results to the interpreted parser. Every time. What changed: -- Rewrote the CST/AST code generator from the ground up to structurally mirror the interpreter's control flow. Identified and fixed 7 behavioral divergences in whitespace handling, predicate evaluation, cut failure propagation, and token boundary tracking. -- Fixed generated parsers crashing with StackOverflowError when the whitespace directive references named rules like LineComment or BlockComment. Added a reentrant guard matching the interpreter's approach. -- Fixed generated Token nodes losing their rule names. Tokens from < > captures now carry the parent rule name (e.g., "SelectKW", "NumericType") instead of a generic "token". -- Fixed CST tree structure. Container expressions (ZeroOrMore, OneOrMore, Optional) now wrap their children in proper NonTerminal nodes instead of flattening them into the parent -- matching how the interpreter builds the tree. -- Added 40 conformance tests that run the same grammars and inputs through both the interpreted and generated parsers, asserting identical success/failure outcomes. These fixes were discovered while building a PostgreSQL SQL parser with peglib. The interpreted parser handled the full grammar correctly, but the generated standalone parser had subtle failures. Now both produce matching results on all 350 tests. Test count: 308 -> 350 pragmatica-lite dependency: 0.9.10 -> 0.24.0 Available on Maven Central: <groupId>org.pragmatica-lite</groupId> <artifactId>peglib</artifactId> <version>0.2.1</version> GitHub: https://lnkd.in/dgdjZahV #java #parsing #peg #opensource #compilers
To view or add a comment, sign in
-
🚀 Problem Solved: Two Sum (Java) Today I solved the classic Two Sum problem using Java and HashMap. Instead of using a brute-force approach with nested loops (O(n²)), I optimized the solution using a HashMap to achieve O(n) time complexity. 🔹 Key Idea: While iterating through the array, store each number and its index in a HashMap. For every element, calculate the complement (target − current value) and check if it already exists in the map. If it exists, we found the pair of indices that add up to the target. #DSA #DataStructures #Algorithms #CodingInterview #ProblemSolving 💡 Concepts Used: HashMap Time Complexity Optimization Problem Solving with Data Structures This approach improves performance and is commonly asked in coding interviews. #Java #DSA #ProblemSolving #CodingInterview #LeetCode #HashMap #SoftwareDevelopment Problem Explanation (You can add in comments or description) Problem: Given an array nums and an integer target, return the indices of two numbers such that they add up to the target. Example: nums = [2,7,11,15] target = 9 Output = [0,1] Because: nums[0] + nums[1] = 2 + 7 = 9 Approach Used (HashMap – Optimal) Create a HashMap to store numbers and their indices. Loop through the array. For each number: Calculate complement = target - nums[i] Check if the complement exists in the HashMap. If yes → return the stored index and current index. Otherwise store the current number and index in the map.
To view or add a comment, sign in
-
-
📌 Collectors in Java Streams — Transforming Data Efficiently Collectors are used with streams to transform and gather results into collections or other structures. They are mainly used with: collect() — a terminal operation --- 1️⃣ What is collect()? collect() converts a stream into a final result like: • List • Set • Map • Grouped data Example: List<Integer> list = stream.collect(Collectors.toList()); --- 2️⃣ Common Collectors 🔹 toList() Convert stream to List list.stream() .collect(Collectors.toList()); --- 🔹 toSet() Removes duplicates list.stream() .collect(Collectors.toSet()); --- 🔹 toMap() Convert to Map list.stream() .collect(Collectors.toMap( key -> key.getId(), value -> value )); --- 3️⃣ groupingBy (Very Important) Groups elements based on a key Example: Map<String, List<Employee>> map = employees.stream() .collect(Collectors.groupingBy( e -> e.getDepartment() )); --- 4️⃣ counting() Counts elements long count = list.stream() .collect(Collectors.counting()); --- 5️⃣ joining() Joins strings String result = list.stream() .collect(Collectors.joining(", ")); --- 6️⃣ Why Collectors Are Powerful ✔ Transform data easily ✔ Replace complex loops ✔ Enable grouping and aggregation ✔ Improve readability --- 🧠 Key Takeaway Collectors turn streams into meaningful results. They are essential for data transformation and aggregation. #Java #Java8 #Streams #Collectors #BackendDevelopment
To view or add a comment, sign in
-
What is var? var lets the compiler infer the data type of a local variable from the assigned value. With Java’s Local Variable Type Inference (var), we can write cleaner and more readable code — but only if we understand its boundaries. According to Oracle Docs: 🔗 https://lnkd.in/dzPr83eS Here are 8 practical rules every Java developer must know 1. Works with Different Data Types var name = "Alok"; // String var age = 19; // int var salary = 50000.5; // double Compiler infers the type at compile time. 2. Only for Local Variables public void demo() { var x = 10; // ✅ valid } var is limited to local scope only. 3. Not for Instance or Global Variables class Test { var x = 10; // ❌ compile-time error } 4. Not a Generic Type var list = new ArrayList<String>(); // ✅ var<String> list = new ArrayList<>(); // ❌ 5. No Explicit Generic Declaration with var You can’t mix var with explicit type parameters. ⚠️ 6. Must Be Initialized var x; // ❌ error Compiler needs a value to infer the type. 7. Not Valid for Lambda (Without Target Type) var f = () -> {}; // ❌ error Lambdas require a target type. 8. Not for Method Parameters or Return Types public var getData() { } // ❌ 💡 Key Insight: var reduces boilerplate but Java is still strongly typed — the type is inferred at compile time, not dynamic. Pro Tip: Use var when the type is obvious → avoid it when readability suffers. A big thank you to my mentor Syed Zabi Ulla & PW Institute of Innovation for continuous support and guidance. Your insights and encouragement have played a huge role in shaping my learning journey. #Java #Programming #Developers #Coding #JavaTips #SoftwareEngineering #Learning
To view or add a comment, sign in
-
-
🚀 Day 6: Deep Dive into Java Data Types – Managing Memory & Structure 🧠💻 Today’s focus was on the building blocks of Java—understanding how data is stored and managed. This is a crucial step because efficient data handling directly impacts application performance. Here’s a breakdown of my learning: 🔹 Primitive Data Types (The Foundation) 🧱 These are predefined and memory-efficient with fixed sizes: 👉 Numerical & Logical Types: byte (1 byte | -128 to 127) short (2 bytes) int (4 bytes) – Most commonly used long (8 bytes) – For large values char (2 bytes) – Stores single characters (Unicode) boolean (1 bit) – true/false 👉 Decimal (Floating Point) Types: float (4 bytes) – Basic precision double (8 bytes) – Preferred for accurate calculations 🔹 Non-Primitive Data Types (The Structures) 🏗️ These are reference types that provide flexibility and scalability: String – Handling text data Arrays – Storing multiple values of the same type Classes & Objects – Core of Object-Oriented Programming Collections – Dynamic data handling using Lists, Sets, etc. 💡 Key Insight: Choosing the right data type is not just about syntax—it’s about optimizing memory, improving performance, and writing scalable code. Every concept like this strengthens my foundation as I move toward becoming a Full Stack Java Developer. 🔥 On to the next step in the journey! #JavaFullStack #DataTypes #CodingJourney #LearningInPublic #BackendDevelopment #SoftwareEngineering #Java #10000Coders #Meghana M
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
GitHub link: https://github.com/Asad12666/DSA-Java/tree/main/src/DataStructures