/**
* Returns a <code>Boolean</code> with a value represented by the
* specified string. The <code>Boolean</code> returned represents a
* true value if the string argument is not <code>null</code>
* and is equal, ignoring case, to the string {@code "true"}.
*
* @param s a string.
* @return the <code>Boolean</code> value represented by the string.
*/
public static Boolean valueOf(String s) {
return toBoolean(s) ? TRUE : FALSE;
}
public class BigInteger extends Number implements Comparable<BigInteger> {
/**
* Returns a positive BigInteger that is probably prime, with the
* specified bitLength. The probability that a BigInteger returned
* by this method is composite does not exceed 2<sup>-100</sup>.
*
*/
public static BigInteger probablePrime(int bitLength, Random rnd) {
if (bitLength < 2)
throw new ArithmeticException("bitLength < 2");
// The cutoff of 95 was chosen empirically for best performance
return (bitLength < SMALL_PRIME_THRESHOLD ?
smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :
largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));
}
public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E>
implements Cloneable, java.io.Serializable
{
/**
* Creates an empty enum set with the specified element type.
*
* @param elementType the class object of the element type for this enum
* set
* @throws NullPointerException if <tt>elementType</tt> is null
*/
public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) {
Enum[] universe = getUniverse(elementType);
if (universe == null)
throw new ClassCastException(elementType + " not an enum");
if (universe.length <= 64)
return new RegularEnumSet<E>(elementType, universe);
else
return new JumboEnumSet<E>(elementType, universe);
}
}
class RegularEnumSet<E extends Enum<E>> extends EnumSet<E> {
}
class JumboEnumSet<E extends Enum<E>> extends EnumSet<E> {
}
public class Collections {
/**
* Returns an unmodifiable view of the specified map. This method
* allows modules to provide users with "read-only" access to internal
* maps. Query operations on the returned map "read through"
* to the specified map, and attempts to modify the returned
* map, whether direct or via its collection views, result in an
* <tt>UnsupportedOperationException</tt>.<p>
*
*/
public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
return new UnmodifiableMap<K,V>(m);
}
private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
}
public enum TimeUnit {
MILLISECONDS {
public long toNanos(long d) { return x(d, C2/C0, MAX/(C2/C0)); }
public long toMicros(long d) { return x(d, C2/C1, MAX/(C2/C1)); }
public long toMillis(long d) { return d; }
public long toSeconds(long d) { return d/(C3/C2); }
public long toMinutes(long d) { return d/(C4/C2); }
public long toHours(long d) { return d/(C5/C2); }
public long toDays(long d) { return d/(C6/C2); }
public long convert(long d, TimeUnit u) { return u.toMillis(d); }
int excessNanos(long d, long m) { return 0; }
},
SECONDS {
.....
},
MINUTES {
.....
},
HOURS {
......
},
DAYS {
.....
};
// TimeUnit.sleep()用来替代Thread.sleep()
public void sleep(long timeout) throws InterruptedException {
if (timeout > 0) {
long ms = toMillis(timeout);
int ns = excessNanos(timeout, ms);
Thread.sleep(ms, ns);
}
}
public abstract class AbstractMap<K,V> implements Map<K,V> {
/**
* Each of these fields are initialized to contain an instance of the
* appropriate view the first time this view is requested. The views are
* stateless, so there's no reason to create more than one of each.
*/
transient volatile Set<K> keySet = null;
public Set<K> keySet() {
if (keySet == null) {
keySet = new AbstractSet<K>() {
.....
};
}
return keySet;
}
}
public class LinkedHashMap<K,V>
extends HashMap<K,V>
implements Map<K,V>
{
/**
* It causes newly allocated entry to get inserted at the end of the linked list and
* removes the eldest entry if appropriate.
*/
void addEntry(int hash, K key, V value, int bucketIndex) {
createEntry(hash, key, value, bucketIndex);
// Remove eldest entry if instructed, else grow capacity if appropriate
Entry<K,V> eldest = header.after;
if (removeEldestEntry(eldest)) {
removeEntryForKey(eldest.key);
} else {
if (size >= threshold)
resize(2 * table.length);
}
}
/**
* Returns <tt>true</tt> if this map should remove its eldest entry.
* This method is invoked by <tt>put</tt> and <tt>putAll</tt> after
* inserting a new entry into the map.
*
* Sample use:
* <pre>
* private static final int MAX_ENTRIES = 100;
*
* protected boolean removeEldestEntry(Map.Entry eldest) {
* return size() > MAX_ENTRIES;
* }
* </pre>
*
*/
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return false;
}
——可以继承LinkedHashMap,覆盖其removeEldestEntry方法。
注:如果想要缓存中的对象只要不被引用,就自动清理;则可以用WeakHashMap
5. 如果指定了toString返回值的格式,则应该提供一个对应的静态工厂方法或构造函数
BigInteger.toString()
12345678910111213
/**
* Returns the String representation of this BigInteger in the
* given radix.
*
*/
public String toString(int radix) {
/**
* Returns the decimal String representation of this BigInteger.
*/
public String toString() {
return toString(10);
}
对应的构造函数如下。这样程序员能容易地在对象及其字符串表示之间来回转换
123456789101112
/**
* Translates the decimal String representation of a BigInteger into a
* BigInteger.
*/
public BigInteger(String val) {
this(val, 10);
}
/**
* Translates the String representation of a BigInteger in the specified
* radix into a BigInteger.
*/
public BigInteger(String val, int radix) {
/**
* Returns a BigInteger whose value is {@code (-this)}.
*
* @return {@code -this}
*/
public BigInteger negate() {
return new BigInteger(this.mag, -this.signum);
}
public static final BigInteger ZERO = new BigInteger(new int[0], 0);
public static final BigInteger ONE = valueOf(1);
public static final BigInteger TEN = valueOf(10);
/** Cache the hash code for the string */
private int hash; // Default to 0
public int hashCode() {
int h = hash;
int len = count;
if (h == 0 && len > 0) {
int off = offset;
char val[] = value;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
设计模式
1. Template Method
Arrays.sort()
123456789101112
// Arrays
public static void sort(Object[] a) {
...
ComparableTimSort.sort(a);
}
// ComparableTimSort
static void sort(Object[] a, int lo, int hi) {
...
binarySort(a, lo, hi, lo + initRunLen);
}
123456789101112131415161718192021
//算法框架
private static void binarySort(Object[] a, int lo, int hi, int start) {
assert lo <= start && start <= hi;
if (start == lo)
start++;
for ( ; start < hi; start++) {
@SuppressWarnings("unchecked")
Comparable<Object> pivot = (Comparable) a[start];
// Set left (and right) to the index where a[start] (pivot) belongs
....
while (left < right) {
int mid = (left + right) >>> 1;
if (pivot.compareTo(a[mid]) < 0) //compareTo这个算法步骤,是由各个Comparable的子类定义的
right = mid;
else
left = mid + 1;
}
....
}
}
//算法框架
public int read(byte b[], int off, int len) throws IOException {
...
int c = read();
...
}
//算法步骤由子类实现
public abstract int read() throws IOException;
JFrame.paint()
123456789101112131415161718192021222324
// JFrame
public void update(Graphics g) {
paint(g);
}
public class MyFrame extends JFrame {
public MyFrame(){
super();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300,300);
this.setVisible(true);
}
@Override
public void paint(Graphics g){ //重定义算法步骤
super.paint(g);
g.drawString("I rule !", 100, 100);
}
public static void main(String[] args){
MyFrame frame = new MyFrame();
}
}
Applet.init()/start()/stop()/destroy()/paint()
123456789101112131415161718192021222324252627
// Applet
public void init() { //什么也不做的hook
}
// Beans
public static Object instantiate(ClassLoader cls, String beanName,
BeanContext beanContext, AppletInitializer initializer)
throws IOException, ClassNotFoundException {
// If it was deserialized then it was already init-ed.
// Otherwise we need to initialize it.
if (!serialized) {
// We need to set a reasonable initial size, as many
// applets are unhappy if they are started without
// having been explicitly sized.
applet.setSize(100,100);
applet.init(); //调用hook
}
}
return result;
}
/**
* Creates a <tt>FutureTask</tt> that will upon running, execute the given <tt>Callable</tt>.
*/
public FutureTask(Callable<V> callable) {
sync = new Sync(callable);
}
/**
* Creates a <tt>FutureTask</tt> that will upon running, execute the given <tt>Runnable</tt>
*/
public FutureTask(Runnable runnable, V result) {
sync = new Sync(Executors.callable(runnable, result));
}
Executors.callable()返回Adapter对象:
12345678910111213141516171819
public static <T> Callable<T> callable(Runnable task, T result) {
return new RunnableAdapter<T>(task, result);
}
/** --Adapter!--
* A callable that runs given task and returns given result
*/
static final class RunnableAdapter<T> implements Callable<T> { //Target
final Runnable task; //Adaptee
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
task.run();
return result;
}
}
AbstractExecutorService.submit()也用到了这个Adapter:
123456789
public <T> Future<T> submit(Runnable task, T result) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task, result);
execute(ftask);
return ftask;
}
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}