赞
踩
by Joshua Bloch
I, Michael Parker, own this book and took these notes to further my own learning. If you enjoy these notes, please purchase the book!
Type
are put in a non-instantiable class named Types
.getInstance
may return the same instance, while newInstance
should not.Builder<T>
interface.implements Serializable
to a singleton class is not enough, you must declare all fields transient
and provide a readResolve
method.enum
type provides the serialization for free and is the best way to implement a singleton.equals覆盖equals时请遵循通用约定
equals
when a class has a notion of logical equality that differs from mere object identity, and the superclass has not provided a suitable implementation.Integer
or Date
, the equals
method should always be overridden.equals
contract.equals
contract.float
and double
values, use the Float.compare
and Double.compare
methods to deal with NaN
and -0.0
values.hashCode
when you override equals重写hashCode方法时记得重写equals方法
float
and double
values, use Float.floatToIntBits
and Double.doubleToLongBits
, respectively.toString始终要覆盖toString
String
parameter so a client can convert between the two forms.toString
, or clients may try to parse the string to retrieve it.Comparable考虑实现Comparable接口
equals
method, there is no way to extend and instantiable class with a new value component while preserving the compareTo
contract.compareTo
is consistent with equals
, note that sorted collections (e.g. TreeSet
, TreeMap
) use the equality test imposed by compareTo
instead of equals
and may break the interface (e.g. Set
, Map
) contract.Double.compare
and Float.compare
instead of relational operators, which don't obey the compareTo
contract for floating point values.public static final
fields to immutable objects, public classes should have no public fields.final
to ensure correct behavior when passing an instance between threads without synchronization.readResolve
methods when needed.StringBuilder
for String
).AbstractMap.SimpleEntry
.static import
facility for brevity.private static final
field so a new instance is not created upon every call.List<E>
is read as "list of E", and List<String>
is read as "list of string", where String
is the actual type parameter and E
is the formal type parameter.List
could be designated to hold only types of a single class but opts out of type-checking, List<Object>
is typesafe because it explicitly states that it can contain objects of any type.List<?>
, represents a list of some unknown type and so forbids inserting any element other than null
, unlike the raw type List
which is not typesafe.@SuppressWarnings
annotation on the smallest scope possible, to not mask other, critical warnings.Sub[]
is a subtype of Super[]
, and reified, so they retain their type-information at runtime and Super[]
can throw an ArrayStoreException
when given a different subclass; by contrast, List<E>
is covariant and erased.List<E>
provides compile-time safety but not runtime safety.Object
, and then let a generic singleton factory method cast it to the caller's desired type.<T extends Comparable<T>>
may be read as "for every type T that can be compared to itself" and is the definition of a mutually comparable type.T
producer, use <? extends T>
; if a parameterized type represents a T
consumer, use <? super T>
.Comparator<? super T>
in preference to Comparator<T>
.Class
type is the dynamic analog of Java's cast operator, throwing a ClassCastException
if the operation fails.java.util.Collections
use this method with type tokens to enforce, at runtime, that invalid types are not added to a collection through its raw type.enum
instead of int
constants使用枚举代替int常量enum
type without recompiling its clients because the constant values are not compiled into the clients as they are with the int enum pattern.toString
method of an enum
type, consider writing a fromString
method, similar to how the static valueOf
method would perform if you had not overridden toString
.enum
values, move each implementation into a private nested enum
, and pass an instance of this strategy enum to the constructor of the top-level enum
.EnumSet
instead of bit fields使用EnumSet代替位域EnumSet
is represented by one or more long
values, and so many of its operations are effiiciently performed with bitwise arithmetic.EnumMap
instead of ordinal indexing用EnumMap代替序数索引enum
, it is your responsibility to use the correct int
value, as no type safety is afforded.EnumMap
contains an array internally, offering the speed of an ordinal-indexed array with the type safety and richness of the Map
interface.EnumMap<..., EnumMap<...>>
, which is internally represented as an array of arrays.<T extends Enum<T> & InterfaceName>
.enum
type to another, the functionality must be encapsulated in a helper class or a static helper method.Retention
and Target
for annotation type declarations are called meta-annotations.Override
annotation坚持使用override注解@Override
annotation when a concrete class overrides an abstract method, i.e. implements it, because a differing signature will be caught by the compiler anyway.-enableassertions
command line flag, instead of explicitly throwing exceptions.clone
method to make a defensive copy of a constructor parameter whose type is subclassable by untrusted parties.enum
types to boolean parameters.null
from an array or collection-valued method complicates the caller logic, and usually the callee's.java.util.Collections
, or create a static empty array which is necessarily immutable.{@code}
tag wrapped inside an HTML <pre>
tag.{@literal}
tag is like the {@code}
tag in that it eliminates the need to escape HTML metacharacters, but doesn't render the contents in monospaced font.Iterable
interface even if it does not implement Collection
.for
loop cannot be used if you need to remove elements through an iterator, reassign elements through a list iterator, or iterate over collections in parallel.java.lang
and java.util
(particularly the collections framework), and to a lesser extent java.io
and java.util.concurrent
.float
and double
if exact answers are required需要精确的结果时避免使用float和doubleBigDecimal
can contain decimal values of arbitrary size and provides eight rounding modes, which is ideal for business calculations with legally mandated rounding behavior.int
provides up to nine decimal digits, while long
provides up to eighteen.==
on two boxed primitives, because this always performs identity comparison, while the <
and >
operators compare the underlying primitive values.NullPointerExceptions
.StringBuilder
is to try processing the strings one at a time to avoid all concatenation.static final
fields whose values are immutable should be in uppercase with words separated by underscores.toType
, while methods that return a view have the format asType
, and methods that return a primitive representation have the format typeValue
.hasNext
for class Iterator
.null
, if the object is accessed by multiple threads or if the state-testing method duplicates the work of the state-dependent method.Error
subclasses, and don't define a throwable that does not subclass Exception
or RuntimeException
.NullPointerException
instead of an IllegalArgumentException
if a caller passes in a null
parameter where prohibited.IndexOutOfBoundsException
instead of an IllegalArgumentException
if the caller passes in an invalid index for a sequence.initCause
method of Throwable
.throws
keyword to include unchecked exceptions in a method declaration.toString
method, or "detail message," should contain the values of all the parameters and fields contributing to the exception.synchronized
or visibility is not guaranteed.synchronized
region, do not invoke a method that is provided by the client as a function object, or can be overriden.Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。