Effective Java(第2版)学习笔记
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
可以参考这篇文章:使用Builder解决构造函数参数过多的问题
Item 3: Enforce the singleton property with a private constructor or an enum type
可以参考这篇文章: Java设计模式–单例模式
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
当引用不再需要的时候,赋给其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
若x,y,z都是非null引用:
1. Reflexive(自反性):x.equals(x) 必须返回true
2. Symmetric(对称性):x.equals(y)返回true,当且仅当y.equals(x)返回true
3. Transitive(传递性):x.equals(y)返回true,且y.equals(z)返回true,那么x.equals(z)也返回true
4. Consistent(一致性):多次调用x.equals(y)后,要么都返回true,要么都返回false
Item 9: Always override hashCode
when you override equals
Item10: Always override toString
Item 11: Override clone
judiciously
复制构造函数:
public Yum(Yum yum);
复制工厂方法:
public static Yum newInstance(Yum yum);
Item 12: Consider implementing Comparable
对于基本类型的比较,用”<”和”>”
对于float和double型,用Float.compare和Double.compare
Chapter 4 Classes and Interfaces
Item 13: Minimize the accessibility of classes and members
访问性由低到高:
private
->default
->protected
->public
- 子类中方法的可访问性必须大于等于父类中所覆盖(
override
)的方法 - 如果一个类实现了一个接口,则与接口中同名的方法必须为
public
Item 14: In public classes, use accessor methods, not public fields
accessor methods: getters
mutators: setters
Item 15: Minimize mutability
在多步操作的时候(如循环中),用可变类型代替不可变类型,这样可以提高性能。
例如,在for
循环中,用StringBuilder
代替String
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
非静态内部类实例必须通过外部实例来创建
Chapter 5 Generics
Item 23: Don’t use raw type in new code
用List< E>而不是List。
List< String>是List的子类,但不是List< Object>的子类。
Item 24: Eliminate unchecked warnings
Item 25: Prefer lists to arrays
array(数组)是协变类型,如果Sub是Super的子类,那么Sub[]也是Super[]的子类。
Generics(泛型)是非协变类型,List< Type1>gen Listt< Type2>没有任何关系。
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
如果函数的返回类型是泛型,则需要在函数修饰符和返回类型之间加上< E>:
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>和<? super E>都是限界通配符(bounded wildcard),extends用于指定上界,super用于指定下界。
两条准则:
PECS:生产者(producer)用extends,消费者(consumer)用super
所有的comparable和comparator都是消费者
Item 29: Consider typesafe heterogeneous containers
String.class
的泛型是Class<String>
Integer.class
的泛型是Class<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
反序列化是一个隐式的构造函数。