Essential Java Collections and Exception Handling Tutorial
1. ArrayList Class – add
, get
, set
, remove
, size
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("A"); // add
list.add("B");
String item = list.get(1); // get
list.set(0, "C"); // set
list.remove("B"); // remove by value
int sz = list.size(); // size
2. Looping through an ArrayList
// Index-based loop
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i));
}
// Enhanced for
for(String s : list) {
System.out.println(s);
}
// Using Iterator
import java.util.Iterator;
Iterator<String> it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
3. Sorting an ArrayList
import java.util.Collections;
Collections.sort(list); // Sorts in natural order
4. LinkedList
import java.util.LinkedList;
LinkedList<String> llist = new LinkedList<>();
llist.add("Dog");
llist.addFirst("Cat");
llist.addLast("Parrot");
llist.remove("Cat");
System.out.println(llist);
5. HashMap – Key, Value Pair
import java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
map.put("John", 24);
map.put("Jane", 32);
int age = map.get("John");
map.remove("Jane");
6. HashSet – add, remove, contains
import java.util.HashSet;
HashSet<String> set = new HashSet<>();
set.add("Red");
set.add("Blue");
set.remove("Red");
boolean hasBlue = set.contains("Blue");
7. Iterator
Iterator<String> iter = set.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
8. Map.EntrySet – Iterating a HashMap
for(java.util.Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
9. Java Exception Handling
try {
int result = 10 / 0;
} catch(ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Cleanup code always runs!");
}
10. throw
and throws
Keywords
public void checkAge(int age) throws Exception {
if(age < 18) {
throw new Exception("Underage not allowed");
}
}