Understanding Common Methods in List, ArrayList, HashMap, and
HashSet with Examples
1. List
add(): Adds an element to the list.
get(): Retrieves an element at a specific index.
remove(): Removes an element from the list.
size(): Returns the number of elements in the list.
sort(): Sorts the list.
reverse(): Reverses the 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
put(key, value): Adds or updates a key-value pair.
get(key): Retrieves the value for a given key.
remove(key): Removes the key-value pair for a given key.
containsKey(key): Checks if the key exists.
containsValue(value): Checks if the value exists.
size(): Returns the number of key-value pairs.
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
add(): Adds an element if it is not already present.
remove(): Removes the element.
contains(): Checks if an element is present.
size(): Returns the number of elements.
isEmpty(): Checks if the set is empty.
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.