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.*;
public class ListVsSet {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
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"));
System.out.println("List: " + list);
System.out.println("Set: " + set);
}
}
2. HashSet vs TreeSet
HashSet is unordered and faster. TreeSet is sorted and maintains ascending order.
Example Code:
Set<String> hashSet = new HashSet<>();
Set<String> treeSet = new TreeSet<>();
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:
List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
arrayList.add("A");
arrayList.add("B");
arrayList.add(1, "C");
linkedList.add("X");
linkedList.add("Y");
linkedList.remove("X");
System.out.println("ArrayList: " + arrayList);
System.out.println("LinkedList: " + linkedList);
4. HashMap vs TreeMap vs LinkedHashMap
All are key-value maps but behave differently in terms of order and performance.
Example Code:
Map<Integer, String> hashMap = new HashMap<>();
Map<Integer, String> treeMap = new TreeMap<>();
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
hashMap.put(3, "Three");
hashMap.put(1, "One");
treeMap.put(3, "Three");
treeMap.put(1, "One");
linkedHashMap.put(3, "Three");
linkedHashMap.put(1, "One");
System.out.println("HashMap: " + hashMap);
System.out.println("TreeMap: " + treeMap);
System.out.println("LinkedHashMap: " + linkedHashMap);