ArrayList without copy overhead?

Does anyone know of a List implementation that has a constant get (int index) time (Ie implements RandomAccess ), but don't need to copy the entire list when it grows like ArrayList does?

I think the implementation may be in terms of other lists, for example.

public class ChunkedList<T> implements List<T>, RandomAccess {
  private LinkedList<ArrayList<T>> chunks;
  public T get(int index) {
    return findCorrectChunk(index).get(computeChunkIndex(index));
  }
}
+3
source share
7 answers

If such a structure existed, everyone would use it instead of arrays.

, . / O (sqrt (N)), N , O (N). - O (sqrt (N)). .

N , sqrt (N) sqrt (N) (, ). , sqrt (N). , , ( ), ( ). .

i- , k, , k.. sqrt(N)-1. , ( ). - . , , , .

, ( O (sqrt (N)), . sqrt (N) : X N/X . min (X + N/X) X = sqrt (N).

(i.e, sqrt (N) ), sqrt (N), . O (N). - O (sqrt (N)) .

, O (sqrt (N)). . O (1).

. , , , . . OP , , , - .

+2

, , . . ( ..).

. (, ), . , , .

(, LinkedList , .)

+1

, , TreeMap. ChunkedList warapper . TreeMap Integer Long . o (log (n)) ( , , n). TreeMap LinkedList, .. .

EDIT: - :

public class ChunkedList<T> implements List<T>, RandomAccess {

    private TreeMap<Integer, T> data = new TreeMap<Integer, T>();

    public T get(int index) {
        return data.get(index);
    }

    public boolean add(T o) {
        data.put(data.size() + 1, o);
        return true;
    }

       // Other operations

}

, , ArrayList.

0

ArrayList?

0

. O (1) O (log (n)) .

, - /.

0

. add() , ? ArrayList , , , .

, , .

0

It is not possible to write such a data structure. The closest you can get is the preliminary size of the ArrayList array to its maximum size, assuming you know max. Interestingly, algorithms such as Collections.sort () will perform worse on ChunkedListif checked RandomAccess.

0
source

Source: https://habr.com/ru/post/1716977/


All Articles