5. JavaコアAPIとは
• JDKをインストールするとついてくる src.zip
• Java SE Development Kit 8u131
コメント+空行が約53.6%
7,650
1,087,643
1,004,582
251,013
2,343,238
Files
Lines of Code Effective
Lines of Code Comment
Lines of Code Blank
Lines of Code Total
9. NullPointerException ダメ。ゼッタイ。
外からやってくるものは必ず null チェック!
例:java.util.Arrays LL.3998-4007
public static int hashCode(char a[]) {
if (a == null)
return 0;
int result = 1;
for (char element : a)
result = 31 * result + element;
return result;
}
16. メソッドは短くシンプルに
例:java.util.ArrayList LL.463-480
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
• コメント半分
• 直接関係ないロジックは
サブルーチン化
1
2
3
4
5
31. 立つ鳥跡を濁さず
例:java.util.Timer LL.103-117
/**
* This object causes the timer's task execution thread to exit
* gracefully when there are no live references to the Timer object and no
* tasks in the timer queue. It is used in preference to a finalizer on
* Timer as such a finalizer would be susceptible to a subclass's
* finalizer forgetting to call it.
*/
private final Object threadReaper = new Object() {
protected void finalize() throws Throwable {
synchronized(queue) {
thread.newTasksMayBeScheduled = false;
queue.notify(); // In case queue is empty.
}
}
}; コアAPIの中でも数少ない finalize() のオーバーライド。この
threadReaperはどこからも参照されていないので、このfinalize()が
呼ばれるのはこのTimerインスタンスがお掃除されるとき。このときにちゃ
んと(中で起動している)スレッドを終了させるための仕掛け。