-
Notifications
You must be signed in to change notification settings - Fork 0
Effective Java Reloaded
illyfrancis edited this page Nov 6, 2013
·
2 revisions
- Grammar
- Vocabulary
- Idiom
47, 8, 9, 10, 36, 38 (re-read) 48, 39, 15, 41, 49, 45, 43
- Don't provide mutators
- Ensure the class can't be extended (final and private constructors)
- Make all fields final
- Make all fields private
- Ensure exclusive access to any mutable components (defensive by copying)
- Simple
- Inherently thread-safe
- Can be shared freely
- Can share internals
=> persistent data structure
- Require separate object for each distinct value
- Values vs. Values + Identities
- Only funcation values vs. one nonfunctional value (has null)
-
time / space efficiency vs. < time /space efficiency
When to use boxed primitives
- when API requires it, generics, collection elements etc
- Never export two overloadings with same number of parameters
- Inherently unique instances (e.g. thread)
- 'logical equality' unimportant (e.g. random)
- superclass does the right thing (e.g. collections)
- equals will never be invoked (e.g. private class)
- singletons (also enums)
- reflexivity
- symmetry
- transitivity
- consistency
- non-nullity
You cannot extend an instantiable class and add a value component while preserving the equals contract! => use composition instead of inheritance
public class Person {
final String name, nickname;
final Movie favMovie;
@Override public boolean equals(Object object) {
if (object == this)
return true;
if (object instanceof Person) {
Person that = (Person) Object;
return Objects.equal(this.name, that.name)
&& Objects.equal(this.nickname, that.nickname)
&& Objects.equal(this.favMovie, that.faveMovie);
}
return false;
}
...
}
- Calling hashCode on same object, same JVM , must return the same integer
- if two objects are equal must return same integer on each object
- Want uniform distribution
- refer to book for detail
- or use Guava
return Objects.hashCode(areaCode, prefix, lineNumber);