Understanding Common Methods in List
Understanding Common Methods in List
1. List
Example:
java
Copy code
List<String> list = new ArrayList<>();
list.add("Apple"); // Add an element
list.add("Banana");
System.out.println(list.get(0)); // Output: Apple
list.remove("Apple"); // Remove an element
Collections.sort(list); // Sort the list
Collections.reverse(list); // Reverse the list
2. ArrayList
Inherits all the methods from List, but it's a resizable array.
add(), get(), remove(), size(), sort() also apply here.
Example:
java
Copy code
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(10); // Add an element
arrayList.add(20);
System.out.println(arrayList.get(1)); // Output: 20
arrayList.remove(0); // Remove element at index 0
3. HashMap
Example:
java
Copy code
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 10); // Add a key-value pair
map.put("Banana", 20);
System.out.println(map.get("Apple")); // Output: 10
map.remove("Apple"); // Remove key-value pair
System.out.println(map.size()); // Output: 1
4. HashSet
Example:
java
Copy code
HashSet<String> set = new HashSet<>();
set.add("Apple"); // Add an element
set.add("Banana");
System.out.println(set.contains("Apple")); // Output: true
set.remove("Apple"); // Remove the element
System.out.println(set.size()); // Output: 1
Summary:
Use add() in List, ArrayList, HashSet when you want to insert an element.
Use put() in HashMap to add key-value pairs.
Use get() in List, ArrayList, and HashMap to retrieve elements by index or key.
Use remove() in all collections to remove elements.
Use sort() and reverse() in List and ArrayList to sort or reverse the collection.