Skip to main content

All 90 Items — Quick Reference Index

A complete index of every item in Effective Java (3rd Edition) with links to the relevant chapter documentation.


Chapter 2 — Creating and Destroying Objects

#ItemKey Takeaway
1Consider static factory methods instead of constructorsNamed, cached, flexible return types
2Consider a builder when faced with many constructor parametersUse Builder for 4+ params, especially optional ones
3Enforce the singleton property with a private constructor or an enum typePrefer single-element enum
4Enforce noninstantiability with a private constructorPrivate constructor + AssertionError
5Prefer dependency injection to hardwiring resourcesPass resources via constructor; enables Spring DI
6Avoid creating unnecessary objectsReuse; avoid new String("..."), watch autoboxing
7Eliminate obsolete object referencesNull out stale refs; use weak references in caches
8Avoid finalizers and cleanersImplement AutoCloseable instead
9Prefer try-with-resources to try-finallyCleaner, suppressed exceptions preserved

Chapter 3 — Methods Common to All Objects

#ItemKey Takeaway
10Obey the general contract when overriding equalsReflexive, symmetric, transitive, consistent
11Always override hashCode when you override equalsEqual objects must have equal hash codes
12Always override toStringInclude all interesting fields; provide programmatic access
13Override clone judiciouslyPrefer copy constructors/factories
14Consider implementing ComparableUse Comparator.comparingInt() chaining; never use subtraction

Chapter 4 — Classes and Interfaces

#ItemKey Takeaway
15Minimize the accessibility of classes and membersMake everything as private as possible
16In public classes, use accessor methods, not public fieldsEncapsulate with getters/setters
17Minimize mutabilityAll fields private final; functional operations
18Favor composition over inheritanceWrapper/decorator pattern; avoid fragile subclassing
19Design and document for inheritance or else prohibit itNever invoke overridable methods from constructors
20Prefer interfaces to abstract classesMultiple implementation; mixins; skeletal implementation
21Design interfaces for posterityDefault methods can break existing implementations
22Use interfaces only to define typesAvoid constant interface anti-pattern
23Prefer class hierarchies to tagged classesReplace enum Shape switch with polymorphism
24Favor static member classes over nonstaticNonstatic holds hidden enclosing instance reference
25Limit source files to a single top-level classCompiler-order dependent bugs otherwise

Chapter 5 — Generics

#ItemKey Takeaway
26Don't use raw typesUse List<?> not List; raw types only for class literals & instanceof
27Eliminate unchecked warningsSuppress narrowly with comment justifying safety
28Prefer lists to arraysArrays covariant/reified; generics invariant/erased
29Favor generic typesParameterize your classes
30Favor generic methodsType-safe, flexible utility methods
31Use bounded wildcards to increase API flexibilityPECS: Producer Extends, Consumer Super
32Combine generics and varargs judiciouslyUse @SafeVarargs when truly safe
33Consider typesafe heterogeneous containersClass<T> as typed key; basis of Spring getBean(Class<T>)

Chapter 6 — Enums and Annotations

#ItemKey Takeaway
34Use enums instead of int constantsType-safe; can have methods and data
35Use instance fields instead of ordinalsNever derive meaning from ordinal()
36Use EnumSet instead of bit fieldsType-safe, compact, interoperable
37Use EnumMap instead of ordinal indexingNever use ordinal() to index arrays
38Emulate extensible enums with interfacesEnum implements interface for extensibility
39Prefer annotations to naming patternsType-safe, tool-friendly metadata
40Consistently use the Override annotationCatches wrong-signature bugs at compile time
41Use marker interfaces to define typesBetter than marker annotations when type is needed

Chapter 7 — Lambdas and Streams

#ItemKey Takeaway
42Prefer lambdas to anonymous classesConcise; this refers to enclosing instance
43Prefer method references to lambdas5 types: static, bound, unbound, constructor, array
44Favor the use of standard functional interfaces6 core interfaces; use primitive variants to avoid boxing
45Use streams judiciouslyNot everything should be a stream
46Prefer side-effect-free functions in streamsUse collect; avoid forEach for computation
47Prefer Collection to Stream as a return typeCollection is both Iterable and has stream()
48Use caution when making streams parallelMeasure; wrong data structures degrade performance

Chapter 8 — Methods

#ItemKey Takeaway
49Check parameters for validityUse Objects.requireNonNull, document, fail fast
50Make defensive copies when neededCopy before checking; use immutable types (Instant)
51Design method signatures carefully≤4 params; interface types; enums over booleans
52Use overloading judiciouslyResolution at compile-time; avoid same-arity overloads
53Use varargs judiciouslyRequire ≥1 arg explicitly; mind array allocation cost
54Return empty collections or arrays, not nullsReturn Collections.emptyList() / new Foo[0]
55Return optionals judiciouslyFor absence; never for containers/arrays/primitives
56Write doc comments for all exposed API elements@param, @return, @throws; use {@code}

Chapter 9 — General Programming

#ItemKey Takeaway
57Minimize the scope of local variablesDeclare where first used; prefer for over while
58Prefer for-each loops to traditional for loopsCleaner; works on any Iterable
59Know and use the librariesUse ThreadLocalRandom; know java.util, java.util.concurrent
60Avoid float and double if exact answers are requiredUse BigDecimal, int, or long for money
61Prefer primitive types to boxed primitivesBoxed: identity bugs, NPE, performance cost
62Avoid strings where other types are more appropriateUse enums, typed keys, value types
63Beware the performance of string concatenationUse StringBuilder in loops
64Refer to objects by their interfacesSet<> not HashSet<>; enables impl swap
65Prefer interfaces to reflectionCreate reflectively; access via interface
66Use native methods judiciouslyJVM is fast; native methods reduce portability and safety
67Optimize judiciouslyWrite good programs first; profile before optimizing
68Adhere to generally accepted naming conventionsJLS §6.1; HttpUrl not HTTPURL

Chapter 10 — Exceptions

#ItemKey Takeaway
69Use exceptions only for exceptional conditionsNever for control flow
70Use checked exceptions for recoverable conditions and runtime exceptions for programming errorsChecked = recoverable; Runtime = bug
71Avoid unnecessary use of checked exceptionsConsider Optional or state-testing method
72Favor the use of standard exceptionsIAE, ISE, NPE, IOOBE, UOE
73Throw exceptions appropriate to the abstractionException translation with chaining
74Document all exceptions thrown by each method@throws for checked and unchecked
75Include failure-capture information in detail messagesInclude all relevant field values
76Strive for failure atomicityObject unchanged after failed operation
77Don't ignore exceptionsLog or comment; name variable ignored

Chapter 11 — Concurrency

#ItemKey Takeaway
78Synchronize access to shared mutable dataSync both reads AND writes; volatile for visibility only
79Avoid excessive synchronizationNever call alien methods while holding a lock
80Prefer executors, tasks, and streams to threadsExecutorService > raw Thread; Spring @Async
81Prefer concurrency utilities to wait and notifyCountDownLatch, ConcurrentHashMap, BlockingQueue
82Document thread safetyImmutable / unconditional / conditional / not thread-safe
83Use lazy initialization judiciouslyHolder class idiom for statics; double-check for instances
84Don't depend on the thread schedulerNo yield, no busy-wait, no thread priorities for correctness

Chapter 12 — Serialization

#ItemKey Takeaway
85Prefer alternatives to Java serializationUse JSON / protobuf in new systems
86Implement Serializable with great cautionLocks implementation; adds testing burden
87Consider using a custom serialized formSerialize logical state; mark impl fields transient
88Write readObject methods defensivelyDefensive copies + invariant checks
89For instance control, prefer enum types to readResolveEnum singleton is the safest approach
90Consider serialization proxies instead of serialized instancesProxy delegates to public constructor; safest pattern