Effective Java (Second Edition) study notes
Chapter 2 Creating and Destroying Objects
Item 1: Consider static factory methods instead of constructors
Item 2: Consider a builder when faced with many constructor parameters
You can refer to this article: Use Builder to solve the problem of too many constructor parameters
Item 3: Enforce the singleton property with a private constructor or an enum type
You can refer to this article: Java Design Pattern-Singleton Pattern
Item 4: Enforce noninstantiability with a private constructor
Item 5: Avoid creating unnecessary objects
String s = new String("abcdefg"); //bad
String s = "abcdefg"; //good
Item 6: Eliminate obsolete object references
When the reference is no longer needed, assign it to null
public Object pop(){
if(size == 0){
throw new EmptyStackException();
}
Object result = elments[--size];
elements[size] = null; //删除不再需要的引用
return result;
}
Item 7: Avoid finalizers
Chapter 3 Methods Common to All Objects
Item 8: Obey the general contract when overriding equals
If x, y, and z are all non-null references:
1. Reflexive : x.equals(x) must return true
2. Symmetric : x.equals(y) returns true if and only if y.equals (x) returns to true
3. transitive, (transitive): x.equals (y) returns true, and y.equals (z) returns true, then x.equals (z) returns to true
4. the consistent (consistent ): After calling x.equals(y) multiple times, either all return true or all return false
Item 9: Always override hashCode
when you override equals
Item10: Always override toString
Item 11: Override clone
judiciously
Copy constructor:
public Yum(Yum yum);
Copy factory method:
public static Yum newInstance(Yum yum);
Item 12: Consider implementing Comparable
For comparison of basic types, use "<" and ">".
For float and double types, use Float.compare and Double.compare
Chapter 4 Classes and Interfaces
Item 13: Minimize the accessibility of classes and members
Accessibility from low to high:
private
-> default
-> protected
->public
- The accessibility of the method in the subclass must be greater than or equal to
override
the method covered by the parent class ( ) - If a class implements an interface, the method with the same name in the interface must be
public
Item 14: In public classes, use accessor methods, not public fields
accessor methods: getters
mutators: setters
Item 15: Minimize mutability
In the multi-step operation (such as in a loop), replace the immutable type with a mutable type , which can improve performance.
For example, in the for
loop, StringBuilder
replace withString
Item 16: Favor composition over inheritance
Item 17: Design and document for inheritance or else prohibit it
Item 18: Prefer interfaces to abstract classes
Item 19: Use interfaces only to define types
Item 20: Prefer class hierarchies to tagged classes
Item 21: Use function objects to represent strategies
Item 22: Favor static member classes over nonstatic
Non-static inner class instances must be created by external instances
Chapter 5 Generics
Item 23: Don’t use raw type in new code
Use List<E> instead of List.
List<String> is a subclass of List, but not a subclass of List<Object>.
Item 24: Eliminate unchecked warnings
Item 25: Prefer lists to arrays
Array is a covariant type. If Sub is a subtype of Super, then Sub[] is also a subtype of Super[].
Generics is a non-covariant type, and List<Type1>gen Listt<Type2> has nothing to do with it.
Object[] objectArray = new Long[1];
objectArray[0] = "abc"; //运行时才报错
List<Object> ol = new ArrayList<long>(); //编译时就报错
ol.add("abc");
Item 26: Favor generic types
Item 27: Favor generic methods
If the return type of the function is generic , you need to add <E> between the function modifier and the return type :
public static <E> Set<E> union(){
Set<E> set = new HashSet<E>();
...
return set;
}
Item 28: Use bounded wildcards to increase API flexibility
public void pushAll(Iterable<? extends E> src){
...
}
public void popAll(Collection<? super E> des){
...
}
<? extends E> and <? super E> are both bounded wildcards, extends is used to specify the upper bound , and super is used to specify the lower bound .
Two guidelines:
PECS: Producer (producer) uses extends, consumer (consumer) uses super
All comparables and comparators are consumers
Item 29: Consider typesafe heterogeneous containers
String.class
The generic is Class<String>
Integer.class
the generic isClass<Integer>
//Typesafe heterogeneous container pattern - API
public class Favorites{
public <T> void putFavorite(Class<T> type, T instance);
public <T> T getFavorite(Class<T> type);
}
Chapter 6 Enums and Annotations
Item 30: Use enums instead of int
constants
Item 31: Use instance fields instead of ordinals
Item 32: Use EnumSet
instead of bit fields
Item 33: Use EnumMap
instead of ordinal indexing
Item 34: Emulate extensible enums with interfaces
Item 35: Prefer annotations to naming patterns
Item 36: Consistently use the Override
annotation
Item 37: Use marker interfaces to define types
Chapter 7 Methods
Item 38: Check parameters for validity
Item 39: Make defensive copies when needed
Item 40: Design method signatures carefully
Item 41: Use overloading judiciously
在overload
方法中做选择是静态的,在override
方法中做选择是动态的。
Item 42: Use varargs judiciously
Item 43: Return empty arrays or collections, not nulls
Item 44: Write doc comments for all exposed API elements
Chapter 8 General Programming
Item 45: Minimize the scope of local variables
Item 46: Prefer for-each loops to traditional for
loops
Item 47: Know and use the libraries
Item 48: Avoid float
and double
if exact answers are required
float
和double
的结果是准确近似,并不精确。
如果需要精确的结果,应该使用BigDecimal
、int
或long
Item 49: Prefer primitive types to boxed primitives
对包装类使用==
,基本都是错的。
Item 50: Avoid strings where other types are more appropriate
Item 51: Beware the performance of string concatenation
如果改动次数较多,应该使用StringBuilder
Item 52: Refer to objects by their interfaces
Item 53: Prefer interfaces to reflection
Item 54: Use native methods judiciously
Item 55: Optimize judiciously
Strive to write good programs rather than fast ones.
Item 56: Adhere to generally accepted naming conventions
Chapter 9 Exceptions
Item 57: Use exceptions only for exceptional conditions
Item 58: Use checked exceptions for reconverable conditions and runtimeexceptions for programming errors
三种throwable:
- checked exceptions
- runtime exceptions
- errors
调用者如果能恢复,应该使用checked exceptions
用runtime exceptions来提示编程错误
Item 59: Avoid unneccessary use of checked exceptions
Item 60: Favor the use of standard exceptions
Item 61: Throw exceptions appropriate to the abstraction
Item 62: Document all exceptions thrown by each method
Item 63: Include failure-capture information in detail messages
Item 64: Strive for failure atomicity
Item 65: Don’t ignore exceptions
Chapter 10 Concurrency
Item 66: Synchronize access to shared mutable data
Item 67: Avoid excessive synchronization
Item 68: Prefer executors and tasks to threads
Item 69: Prefer concurrency utilities to wait
and notify
Item 70: Document thread safety
Item 71: Use lazy initialization judiciously
Item 72: Don’t depend on the thread scheduler
Item 73: Avoid thread groups
Chapter 11 Serialization
Item 74: Implement Serializable
judiciously
Deserialization is an implicit constructor.