2012-07-12 2 views
5

RandomAccessクラスのjava docには、 "List実装が高速(一般的には一定時間)ランダムアクセスをサポートするために使用するマーカーインタフェースがあります。ランダムアクセスリストまたはシーケンシャルアクセスリストのいずれかに適用されたときに、その動作を変更して良好なパフォーマンスを提供する汎用アルゴリズムAbstractList.javaでのRandomAccessの操作

が、私はいくつかの奇妙なこと

を発見し、これはjava.utilパッケージ内AbstractList.javaにおけるサブリスト方法がある

public List<E> subList(int fromIndex, int toIndex) { 
    return (this instanceof RandomAccess ? 
      new RandomAccessSubList<>(this, fromIndex, toIndex) : 
      new SubList<>(this, fromIndex, toIndex)); 
} 

RandomAccessSubListクラスの実装:

class RandomAccessSubList<E> extends SubList<E> implements RandomAccess { 
    RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) { 
     super(list, fromIndex, toIndex); 
    } 

    public List<E> subList(int fromIndex, int toIndex) { 
     return new RandomAccessSubList<>(this, fromIndex, toIndex); 
    } 
} 

サブリストクラスの実装:

SubList(AbstractList<E> list, int fromIndex, int toIndex) { 
    if (fromIndex < 0) 
     throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); 
    if (toIndex > list.size()) 
     throw new IndexOutOfBoundsException("toIndex = " + toIndex); 
    if (fromIndex > toIndex) 
     throw new IllegalArgumentException("fromIndex(" + fromIndex + 
              ") > toIndex(" + toIndex + ")"); 
    l = list; 
    offset = fromIndex; 
    size = toIndex - fromIndex; 
    this.modCount = l.modCount; 
} 

は、と私はそれがサブリストクラスにそのデータを渡し、およびルートリストが速いので、その動作は、サブリスト方式

答えて

5

new SubList<>(this, fromIndex, toIndex)); 

のようなものですので、AbstractListクラスでは、RandomAccessSubListは、無用であることを考えますランダムなインデックスにアクセスする際には、サブリストもそれを実行するのが速いので、サブリストをRandomAccessとしてマークすることは意味があります。

SubListとRandomAccessSubListは、継承を介して同じ実装を共有しますが、1つはRandomAccessとしてマークされていません。そのため、サブクラスが便利です。

+0

はい、なぜ2つの実装が同じですか? – Pooya

+5

これは 'RandomAccess'とマークされ、もう一つはマークされないようにします。これは、 'Collections.binarySearch'のような操作が、どのアルゴリズムがこれらのパフォーマンス特性を持つリストに対してより効率的であるかを判断するのに役立ちます。 –

+0

私はまだ基​​本的なコンセプトについてはっきりしていません。なぜRandomAccessを実装するのですか? Arrayは、連続したメモリのためにより速いアクセスを提供し、ArrayListは内部的に配列を使用します。 JVMはRandomAccessを実装するリストのために何か追加作業をしていますか? – AKS