🚀 Java Series – Day 23 📌 ArrayList vs LinkedList in Java 🔹 What is it? Both ArrayList and LinkedList are part of the Java Collection Framework and implement the List interface. They are used to store ordered data, but their internal working is different. 🔹 Why do we use it? Choosing the right list improves performance and efficiency. For example: • Frequent searching → ArrayList • Frequent insertion/deletion → LinkedList 🔹 ArrayList vs LinkedList: • ArrayList - Uses dynamic array - Fast for accessing elements (O(1)) - Slow insertion/deletion (shifting needed) • LinkedList - Uses doubly linked list - Slow access (O(n)) - Fast insertion/deletion 🔹 Example: import java.util.*; public class Main { public static void main(String[] args) { List<String> arrayList = new ArrayList<>(); arrayList.add("A"); arrayList.add("B"); List<String> linkedList = new LinkedList<>(); linkedList.add("X"); linkedList.add("Y"); System.out.println(arrayList); System.out.println(linkedList); } } 💡 Key Takeaway: Use ArrayList for fast access and LinkedList for frequent modifications. What do you think about this? 👇 #Java #Collections #ArrayList #LinkedList #JavaDeveloper #Programming
ArrayList vs LinkedList in Java: Choosing the Right List
More Relevant Posts
-
🚀 Day 3 of Java Series 👉 Find common elements between two lists using Streams import java.util.*; import java.util.stream.*; public class CommonElementsExample { public static void main(String[] args) { List<Integer> list1 = List.of(10, 20, 30, 40, 50); List<Integer> list2 = List.of(30, 40, 60, 70); Set<Integer> set2 = new HashSet<>(list2); List<Integer> common = list1.stream() .filter(set2::contains) .toList(); System.out.println(common); // [30, 40] } } 💡 What’s happening here? ✔ Convert one list into a HashSet → O(1) lookup ✔ Stream through list1 ✔ Filter only elements present in list2 ✔ Collect result into a list ⚡ Key Insight: Using List.contains() leads to O(n²) complexity Using HashSet reduces it to O(n + m) 🧠 Interview Tip: Always optimize lookups using HashSet when dealing with search operations 📌 Output: [30, 40] ❓Can you think of a way to handle duplicates in both lists? #Java #Streams #CodingInterview #Developers #JavaDeveloper #Learning #Tech
To view or add a comment, sign in
-
🧠 Java MCQ – Answer Explanation Question Recap Java List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("A"); System.out.println(list.size()); Correct Answer: C) 3 ✅ Step-by-Step Explanation List in Java allows duplicate elements. ArrayList implements the List interface. When elements are added to an ArrayList, they are stored in insertion order. There is no restriction on adding the same value multiple times. ▶ Execution Flow list.add("A"); → List becomes: ["A"] list.add("B"); → List becomes: ["A", "B"] list.add("A"); → List becomes: ["A", "B", "A"] Even though "A" is added twice, it is accepted. 📌 Final Point list.size() returns the total number of elements present, including duplicates. So, total elements = 3 Output: 3 💡 Key Concept to Remember List → allows duplicates Set → does NOT allow duplicates ArrayList → preserves insertion order size() → counts all elements including duplicates #JavaMCQ #CodingMCQ #InterviewPreparation #MNCInterview #CodeAnalysis #ConceptClarity #JavaLearning #ServletJSP #JDBC #OracleDB #DeveloperMindset #PracticeCoding
To view or add a comment, sign in
-
-
🚀 Java Revision Journey – Day 28 Today I revised LinkedHashSet in Java, an important Set implementation that maintains order along with uniqueness. 📝 LinkedHashSet Overview LinkedHashSet is a class in java.util that implements the Set interface. It combines the features of HashSet + Doubly Linked List to maintain insertion order. 📌 Key Characteristics: • Stores unique elements only (no duplicates) • Maintains insertion order • Allows one null value • Internally uses Hash table + Linked List • Implements Set, Cloneable, and Serializable • Not thread-safe 💻 Example LinkedHashSet<Integer> set = new LinkedHashSet<>(); set.add(10); set.add(20); set.add(10); // Duplicate ignored System.out.println(set); // Output: [10, 20] (in insertion order) 🏗️ Constructors Default Constructor LinkedHashSet<Integer> set = new LinkedHashSet<>(); From Collection LinkedHashSet<Integer> set = new LinkedHashSet<>(list); With Initial Capacity LinkedHashSet<Integer> set = new LinkedHashSet<>(10); With Capacity + Load Factor LinkedHashSet<Integer> set = new LinkedHashSet<>(10, 0.75f); 🔑 Basic Operations Adding Elements: • add() → Adds element (maintains insertion order) Removing Elements: • remove() → Removes specified element 🔁 Iteration • Using enhanced for-loop • Using Iterator for (Integer num : set) { System.out.println(num); } 💡 Key Insight LinkedHashSet is widely used when you need: • Maintain insertion order + uniqueness together • Predictable iteration order (unlike HashSet) • Removing duplicates while preserving original order • Slightly better performance than TreeSet with ordering needs 📌 Understanding LinkedHashSet helps in scenarios where order matters along with uniqueness, making it very useful in real-world applications. Continuing to strengthen my Java fundamentals step by step 💪🔥 #Java #JavaLearning #LinkedHashSet #DataStructures #JavaDeveloper #BackendDevelopment #Programming #JavaRevisionJourney 🚀
To view or add a comment, sign in
-
-
📌 TOPIC: Optional Class in Java (Java 8) The Optional class (from java.util) is used to avoid NullPointerException and handle missing values safely. 👉 Instead of using null, we use Optional to represent a value that may or may not be present. 🔸 Why use Optional? 1️⃣ Prevents NullPointerException 2️⃣ Makes code more readable 3️⃣ Forces proper handling of missing values 🔸 Creating Optional Objects import java.util.Optional; Optional<String> opt1 = Optional.of("Hello"); // value must not be null Optional<String> opt2 = Optional.ofNullable(null); // can be null Optional<String> opt3 = Optional.empty(); // empty Optional 🔸 Common Methods ✔️ isPresent() & get() Optional<String> name = Optional.of("Java"); if(name.isPresent()) { System.out.println(name.get()); } ✔️ orElse() Optional<String> name = Optional.ofNullable(null); System.out.println(name.orElse("Default Value")); 👉 Output: Default Value ✔️ ifPresent() Optional<String> name = Optional.of("Java"); name.ifPresent(n -> System.out.println(n)); Key Insight: Optional helps write cleaner and safer code by reducing direct null checks and preventing runtime errors. #Java #Optional #Java8 #Programming #Codegnan #LearningJourney #Developers My gratitude towards my mentor #AnandKumarBuddarapu #SakethKallepu #UppugundlaSairam
To view or add a comment, sign in
-
-
☕ Optional Class in Java 8 The Optional class in Java 8 is used to avoid NullPointerException (NPE). 👉 It is introduced by Oracle Corporation in Java 8. 🧠 Why Optional? 👉 Problem (Before Java 8): String name = null; System.out.println(name.length()); // ❌ NullPointerException 👉 Solution (Using Optional): Optional<String> name = Optional.ofNullable(null); System.out.println(name.orElse("Default")); ✔️ No crash ✔️ Safe handling of null 🔧 How to Create Optional Optional<String> op1 = Optional.of("Java"); // Not null Optional<String> op2 = Optional.ofNullable(null); // Can be null Optional<String> op3 = Optional.empty(); // Empty ⚙️ Important Methods (Must Know 🔥) 1️⃣ isPresent() 👉 Check value exists if(op.isPresent()) { System.out.println(op.get()); } 2️⃣ get() 👉 Get value (⚠️ risky if empty) 3️⃣ orElse() 👉 Default value if null op.orElse("Default"); 4️⃣ orElseGet() 👉 Default using function 5️⃣ orElseThrow() 👉 Throw exception if empty 6️⃣ map() 👉 Transform value op.map(String::toUpperCase); 7️⃣ ifPresent() 👉 Execute if value exists op.ifPresent(System.out::println); 💻 Real Example Optional<String> name = Optional.ofNullable("Ranjit"); name.ifPresent(n -> System.out.println(n)); String result = name.map(String::toUpperCase) .orElse("No Name"); System.out.println(result); 🌟 Advantages ✔️ Avoid NullPointerException ✔️ Clean & readable code ✔️ Functional style coding ⚠️ Best Practices ❌ Don’t use get() without check ❌ Don’t use Optional for fields (avoid overuse) ✔️ Use orElse, orElseGet, ifPresent
To view or add a comment, sign in
-
📘 Follow me for daily Java, Spring Boot, SQL & System Design MCQs to crack MNC interviews 🚀 🧠 Java Interview MCQ — Day 6 Topic: Java Collections Q1. Output of List with duplicates List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("A"); System.out.println(list.size()); Answer: C) 3 Why: ArrayList allows duplicate elements and preserves insertion order. You added 3 items, so size is 3. Q2. Which collection does NOT allow duplicate elements? Answer: C) HashSet Why: HashSet follows Set rules. Set never allows duplicate values. Q3. Method used to sort a List in Java Answer: B) Collections.sort() Why: Collections.sort() sorts a List in natural order or using a Comparator. Q4. Default initial capacity of ArrayList Answer: C) 10 Why: When ArrayList resizes for the first time, it creates capacity of 10. Q5. Which interface is implemented by ArrayList? Answer: C) List Why: ArrayList implements the List interface. Q6. What happens if you add null into HashSet? Answer: B) Only one null allowed Why: HashSet allows a single null value because duplicates are not allowed. Q7. Which class maintains insertion order? Answer: C) LinkedHashSet Why: LinkedHashSet maintains insertion order using a linked list and hash table. Q8. Which of the following is NOT synchronized? Answer: C) ArrayList Why: ArrayList is not thread-safe. Vector, Hashtable, and Stack are synchronized. Q9. Which method removes an element by index in ArrayList? Answer: B) remove() Why: remove(int index) method removes element by index. Q10. Which collection is best for key–value pairs? Answer: C) Map Why: Map is designed for key and value mapping like HashMap, TreeMap, LinkedHashMap. ✅ Concept Summary List → allows duplicates, ordered Set → no duplicates Map → key/value pairs ArrayList → not synchronized, allows duplicates HashSet → one null, no duplicates LinkedHashSet → maintains insertion order #Java #SpringBoot #FullStackDeveloper
To view or add a comment, sign in
-
-
Day 9 Java Practice: Find the First Non-Repeated Character in a String While practicing Java, I worked on a classic string problem: 👉 Find the first non-repeated character in a given string. For example, in the string "swiss", the first character that does not repeat is 'w'. To solve this, I used a LinkedHashMap to store character counts while preserving insertion order. Then I iterated through the map to find the first character with count = 1. ================================================== // Online Java Compiler // Use this editor to write, compile and run your Java code online import java.util.*; class Main { public static void main(String[] args) { String s="swiss"; char[] words=s.toCharArray(); Map<Character,Integer>map=new LinkedHashMap<Character,Integer>(); for(char word:words) { map.put(word,map.getOrDefault(word,0)+1); } for(Map.Entry<Character,Integer>entry:map.entrySet()) { if(entry.getValue()==1) { System.out.println("First non-repeated character in the string is:"+entry.getKey()); break; } } } } Output:First non-repeated character in the string is:w This was a good exercise to understand: Character frequency counting Importance of insertion order using LinkedHashMap String traversal logic #AutomationTestEngineer #Selenium #Java #CodingPractice #ProblemSolving
To view or add a comment, sign in
-
-
Learn about ClassCastException in Java, common scenarios that trigger it, and best practices to avoid this runtime error in your code
To view or add a comment, sign in
-
Learn about ClassCastException in Java, common scenarios that trigger it, and best practices to avoid this runtime error in your code
To view or add a comment, sign in
-
🚀 Java Streams Interview Question Given a list of integers, remove duplicates and return a sorted list using Stream API. import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(5, 3, 8, 1, 3, 5, 9, 2, 8); List<Integer> sortedUniqueNumbers = numbers.stream() .distinct() .sorted() .collect(Collectors.toList()); System.out.println(sortedUniqueNumbers); } } Output: [1, 2, 3, 5, 8, 9] 🔹 distinct() removes duplicate elements 🔹 sorted() arranges the elements in ascending order 🔹 collect(Collectors.toList()) converts the stream back to a list #Java #JavaStreams #CodingInterview #Programming #Developers #SoftwareEngineering #BackendDevelopment
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