AbstractCollectionクラスは,List,Map,Setなどのコレクションクラスの親となる抽象クラスである。多くのメソッドは抽象メソッドとなっており,共通する部分のみ実装されている。
isEmpty()メソッドはコレクションが空であるかどうかを返すものであり,size()メソッドの戻り値が0かどうかで判定している。
contains(Object o)メソッドは,コレクションに引数で渡したオブジェクトoが含まれているかをチェックする。iterator()メソッドで自身のイテレータを取得し,これを使って検索している。チェックするオブジェクトoがnullであった場合,このイテレータにnullが含まれているかどうかで判定している。一方チェックするオブジェクトがnullではない場合は,チェックするオブジェクトoのequals()メソッドを用いて,コレクション内のオブジェクトと比較して判定している。
toArray()メソッドはコレクションに格納されているオブジェクトをObject[]型に変換する。まず,size()メソッドで要素数を調べ,その大きさのObject型配列を作成する。次にiterator()メソッドで自身のイテレータを取得し,すべてのオブジェクトをArrays.copyOf()メソッドによりコピーしている。return文の中で更にイテレータのhaxNext()メソッドをチェックし,さらにオブジェクトが存在する場合は,finishToArrayメソッドを呼び出している。このfinishToArray()メソッドは,このソースプログラムの中段に定義されており,不足した分の配列サイズを拡張している。この部分は(想像にすぎないが),このメソッドを実行している最中にオブジェクトが追加された場合に配列を拡張する必要があるための対応だろう。
toArray(T[] a)メソッドは,Object型配列ではなく,引数で渡されたT型の配列に変換する。一般的にはtoArray(new T[0])のように型を指定して呼び出す。渡された配列サイズが不足する場合は, java. lang. reflect. Array .newInstance( a. getClass() .getComponentType(), size );によって,必要な大きさの配列を作成している。後の処理はtoArray()メソッドと同様の処理である。
privateなメソッドfinishToArray(T[] r, Iterator it)は,上で述べたとおり,イテレータで返されてきたオブジェクトの数がsize()メソッドで返された値より多い場合に,配列を拡張して不足分をコピーする。”Reallocates the array being used within toArray when the iterator returned more elements than expected”(toArrayの中でiteratorから期待より多い要素を返された場合,配列を再割当する)というコメントが入っている。
add(E e)メソッドは無条件にUnsupportedOperationExceptionをスローする実装となっており,サブクラスでオーバーライドしなければこの例外がスローされる。
remove(Object o)メソッドは引数で渡されたオブジェクトoを削除するものである。内部の処理はiterator()メソッドで自身のイテレータを取得し,対象オブジェクトを検索する。そして,みつかったらイテレータオブジェクトのremove()メソッドを呼び出し,trueを返す。みつからなかった場合はfalseを返している。
containsAll(Collection c)は引数のコレクションで渡されたオブジェクトがすべて含まれているかどうかを判定する。引数で渡されたコレクションのイテレータを使いオブジェクトを取り出し,すべてのオブジェクトについて,自身のcontains()メソッドに渡して自身の保持しているコレクションに含まれているかを判定している。一つでもcontains()メソッドがfalseを返した場合はその時点でループから抜けてfalseを返す,メソッドの最後まで到達した場合にはtrueを返している。
addAll(Collection c)メソッドは引数で渡されたコレクションをすべて自身のコレクションに追加する。これもイテレータでループさせて処理している。
removeAll(Collection c)メソッドは引数で渡されたコレクションのオブジェクトをすべて自身のコレクションから削除する。同様にイテレータを使って,ループで処理しイテレータのremove()メソッドで削除する。
* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util;
public abstract class AbstractCollection<E> implements Collection<E> {
protected AbstractCollection() {
}
// Query Operations
public abstract Iterator<E> iterator();
public abstract int size();
public boolean isEmpty() {
return size() == 0;
}
public boolean contains(Object o) {
Iterator<E> it = iterator();
if (o==null) {
while (it.hasNext())
if (it.next()==null)
return true;
} else {
while (it.hasNext())
if (o.equals(it.next()))
return true;
}
return false;
}
public Object[] toArray() {
// Estimate size of array; be prepared to see more or fewer elements
Object[] r = new Object[size()];
Iterator<E> it = iterator();
for (int i = 0; i < r.length; i++) {
if (! it.hasNext()) // fewer elements than expected
return Arrays.copyOf(r, i);
r[i] = it.next();
}
return it.hasNext() ? finishToArray(r, it) : r;
}
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
// Estimate size of array; be prepared to see more or fewer elements
int size = size();
T[] r = a.length >= size ? a :
(T[])java.lang.reflect.Array
.newInstance(a.getClass().getComponentType(), size);
Iterator<E> it = iterator();
for (int i = 0; i < r.length; i++) {
if (! it.hasNext()) { // fewer elements than expected
if (a == r) {
r[i] = null; // null-terminate
} else if (a.length < i) {
return Arrays.copyOf(r, i);
} else {
System.arraycopy(r, 0, a, 0, i);
if (a.length > i) {
a[i] = null;
}
}
return a;
}
r[i] = (T)it.next();
}
// more elements than expected
return it.hasNext() ? finishToArray(r, it) : r;
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE – 8;
@SuppressWarnings("unchecked")
private static <T> T[] finishToArray(T[] r, Iterator<?> it) {
int i = r.length;
while (it.hasNext()) {
int cap = r.length;
if (i == cap) {
int newCap = cap + (cap >> 1) + 1;
// overflow-conscious code
if (newCap – MAX_ARRAY_SIZE > 0)
newCap = hugeCapacity(cap + 1);
r = Arrays.copyOf(r, newCap);
}
r[i++] = (T)it.next();
}
// trim if overallocated
return (i == r.length) ? r : Arrays.copyOf(r, i);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError
("Required array size too large");
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
// Modification Operations
public boolean add(E e) {
throw new UnsupportedOperationException();
}
public boolean remove(Object o) {
Iterator<E> it = iterator();
if (o==null) {
while (it.hasNext()) {
if (it.next()==null) {
it.remove();
return true;
}
}
} else {
while (it.hasNext()) {
if (o.equals(it.next())) {
it.remove();
return true;
}
}
}
return false;
}
// Bulk Operations
public boolean containsAll(Collection<?> c) {
for (Object e : c)
if (!contains(e))
return false;
return true;
}
public boolean addAll(Collection<? extends E> c) {
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator<?> it = iterator();
while (it.hasNext()) {
if (c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator<E> it = iterator();
while (it.hasNext()) {
if (!c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
public void clear() {
Iterator<E> it = iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
}
// String conversion
public String toString() {
Iterator<E> it = iterator();
if (! it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = it.next();
sb.append(e == this ? "(this Collection)" : e);
if (! it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}
}