Java Quick Reference
This quick reference assumes that you already know Java and just want a refresher of some common techniques, particularly for tech interviews.
Contents
Common Stuff
Java 8
Java 8 is a version of Java released in 2014 that brought several new features such as streams and Optional
. This page is written for Java 8.
Collections
ArrayList
A versatile resizable-array implementation of the List
interface.
// initialization, empty
List<String> l = new ArrayList<>();
// initialization from another collection
List<String> anotherList = new ArrayList<>(Arrays.asList("x", "y"));
// Appending, O(1)
l.add("a");
l.add("b");
l.add("c");
l; // = ["a", "b", "c"]
l.size(); // = 3
// Get element at index, O(1)
l.get(1); // = "b"
// Set element at index, O(1)
l.set(1, "x"); // l = ["a", "x", "c"]
// Insert element at index, O(n)
l.add(1, "b"); // l = ["a", "b", "x", "c"];
// Remove element at index, O(n) [but O(1) if last element]
l.remove(2); // l = ["a", "b", "c"]
// Remove element that is equal to a given element
// Uses .equals()
l.remove("b"); // l = ["a", "c"]
// Find first occurence of given element
// Uses .equals()
l.indexOf("c"); // = 1
l.indexOf("orange"); // = -1, not found
// Add multiple elements from another collection
l.addAll(Arrays.asList("x", "y")); // l = ["a", "c", "x", "y"]
// Sublists, a "view" of a part of the list
List<String> subL = l.subList(1, 2); // = ["c", "x"]
l.set(1, "d"); // subL = ["a", "d", "x", "y"]
NOTE:
ArrayList
is not synchronized. If you want a synchronized implementation, you should use Vector
, which is also a resizable-array implementation of List
.HashMap
// initialization
HashMap<String, Integer> hm = new HashMap<>();
// add key value pairs, O(1)
hm.put("orange", 3);
hm.put("banana", 8);
hm; // = {orange=3, banana=8}
hm.size(); // = 3
// accessing values by key, O(1) [absolute worst case O(n)]
hm.get("orange"); // = 3