cheatsheet · while you code
Java traps
Use it when: Before you press Submit, or when the output looks impossible.
One line per trap: the rule to remember. Want to feel each one? Drill them →
Integer, Long and ==
- == on IntegerCompare wrappers with
.equals(), or unbox tointfirst. Never==onInteger. - Comparing HashMap counts
count.get(a).equals(count.get(b)), orObjects.equals(x, y)if a value can be null. - Long.equals(int)Match the types:
total.equals(10L), or compare primitives:total.longValue() == 10. - Missing key into an int
freq.getOrDefault('z', 0)— the safe way to read a count. - new String vs literalAlways compare strings with
.equals(). - Strings built at runtime
.equals()for strings, every time — even when==seemed to work in a small test. - StringBuilder.equalsTurn them into strings first:
x.toString().equals(y.toString()). - Comparing arrays
Arrays.equals(a, b)for 1-D arrays,Arrays.deepEquals(a, b)for 2-D.
Numbers and overflow
- int overflowUse
longwhen a sum can pass about 2 × 10⁹, orMath.addExactto fail loudly. - Binary search midWrite
int mid = lo + (hi - lo) / 2;in every binary search. Bas itna yaad rakho. - int × int into a longCast before you multiply:
(long) a * b, not(long) (a * b). - "Infinity" + 1Skip unreachable states before adding (
if (dist[u] == Integer.MAX_VALUE) continue;), or use a safe infinity like1_000_000_000. - % with negativesUse
Math.floorMod(x, k)(or((x % k) + k) % k) whenever x can be negative. - Math.abs(MIN_VALUE)Go to
longfirst:Math.abs((long) x). Watch for it in "reverse integer" and "divide two integers". - Comparator a - b
Integer.compare(a, b)orComparator.comparingInt(...)— they never overflow. - int / int into a doubleMake one side a double before dividing:
(double) total / count. - 0.1 + 0.2 == 0.3Compare with a tolerance,
Math.abs(a - b) < 1e-9, or keep money in whole paise as along, not rupees as adouble. - << and +Always bracket shifts and masks:
(1 << k) + 1,(n & 1) == 0. - Math.round on halvesIf the problem states a rounding rule, write that rule yourself instead of assuming what
rounddoes.
Strings and chars
- char + 1When you want a letter, cast:
(char) (c + 1). - Digit char to int
c - '0'for a digit,c - 'a'for a letter's index. - 'a' + 'b' + "c"Start with a String (
"" + a + b) or useStringBuilder.append. - toUpperCase() thrown awayKeep the result:
s = s.toUpperCase(); - substring(begin, end)Think
substring(i, i + len)for exactlylencharacters. - split and empty parts
split(",", -1)keeps the trailing empty parts too. - char[].toString()
new String(chars)orString.valueOf(chars);Arrays.toString(chars)only for debugging. - count[ch - 'a'] with capitalsCheck the constraints. If capitals can appear, use
Character.toLowerCase(ch)first, or anint[128]indexed by the char itself.
Collections
- Arrays.asList then add
new ArrayList<>(Arrays.asList(1, 2, 3))when the list must grow. - Arrays.asList(int[])Box it:
Arrays.stream(nums).boxed().collect(Collectors.toList()), or start from anInteger[]. - list.remove(1)To remove a value from a
List<Integer>, pass an object:list.remove(Integer.valueOf(x)). - Removing inside for-each
list.removeIf(x -> x % 2 == 0), or an explicitIteratorwithit.remove(). - Printing a PriorityQueueNeed sorted order? Poll in a loop. Never trust
toStringor for-each on a heap. - Which end is the top?Say it out loud while coding: "min-heap by default; reverseOrder for max".
- Changing a HashMap keyNever change an object after using it as a key. Use immutable keys:
List.of(...), aString, or a number. - HashSet<int[]>For a grid BFS, use
boolean[][] visited, or encode a cell asr * cols + c. - Arrays.fill with a rowMake each row separately:
for (int i = 0; i < n; i++) grid[i] = new int[m]; - push and offer on one dequeOne style per deque: stack =
push / pop / peek, queue =offer / poll / peek. - Stack vs ArrayDeque orderUse
ArrayDeque(evenStack's Javadoc recommendsDeque), and pop when you need top-first order. - TreeSet with tiesBreak ties in the comparator (compare the node id next), or use a
PriorityQueue, which allows duplicates. - Sorting List.of
new ArrayList<>(List.of(...))when you will change it.
Methods and recursion
- Reassign vs mutateTo give back a new array,
returnit. To change the caller's data, change the object, not the variable. - result.add(path)Add a copy:
result.add(new ArrayList<>(path)); - Very deep recursionIf the depth can reach ~10⁴–10⁵ (a long linked list, a skewed tree), use a loop or your own
ArrayDequestack.