Java Collections With Methods and Differences-1
Java Collections With Methods and Differences-1
List vs Set
List allows duplicates and maintains insertion order, while Set does not allow duplicates
and may not maintain order.
Example Code:
import java.util.*;
list.add("Apple");
list.add("Banana");
list.add("Apple"); // Duplicate
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Ignored
list.remove("Banana");
System.out.println("List contains 'Apple'? " + list.contains("Apple"));
Example Code:
hashSet.add("Banana");
hashSet.add("Apple");
hashSet.add("Mango");
hashSet.remove("Banana");
treeSet.add("Banana");
treeSet.add("Apple");
treeSet.add("Mango");
System.out.println("HashSet: " + hashSet);
System.out.println("TreeSet: " + treeSet);
3. ArrayList vs LinkedList
ArrayList is good for fast access, while LinkedList is better for insertions and deletions.
Example Code:
arrayList.add("A");
arrayList.add("B");
arrayList.add(1, "C");
linkedList.add("X");
linkedList.add("Y");
linkedList.remove("X");
Example Code:
hashMap.put(3, "Three");
hashMap.put(1, "One");
treeMap.put(3, "Three");
treeMap.put(1, "One");
linkedHashMap.put(3, "Three");
linkedHashMap.put(1, "One");