Java ArrayList <Double> IndexOutOfBoundsException Problem

I have a problem with ArrayList. I need to save the result. Since I want to start with element n, I tried to provide ArrayListcapacity with ensureCapacity(n+1)for use set(n,x), but I get IndexOutOfBoundsException.

I tried to save n add(x)until using set, and this works.

So, I would like to know why this does not work in my way and how to solve it, because n times is add(x)not a good style; -)

+5
source share
7 answers

list add, . ArrayList , :

final int MAX_ELEMENTS = 1000;
List<Integer> myList = new ArrayList<Integer>(
    Collections.<Integer>nCopies(MAX_ELEMENTS, null));

, , n:

myList.addAll(Collections.<Integer>nCopies(n, null));

( , , Integer, . raw/pre-Java 5, .)

: capacity!= contents. ArrayList , , . , , , . , .

, , , ? API, List s, Arrays.asList. - , .

+6

ArrayList , , . , , .

- , , , .

+7

, ensureCapacity() , .

Java:

, : "... , ( - ) API. , , . , , . , Vector capacityIncrement. , . , . , . , . IdentityHashMap, , "

+2

, securityCapacity() , ArrayList , , , , .

, , ArrayList ...

int n = 10;  //capacity required
ArrayList foo = new ArrayList();

for( int i=0; i<=n; i++ ) {
      foo.add(null);
}

, , .

0

ensureCapacity() . , List . , .

ensureCapacity() .

  • .
  • size ArrayList .

, , , !=

add(..), , size:

ArrayList list = new ArrayList();
list.ensureCapacity(5); // this can be done with constructing new ArrayList(5)

for (int i = 0; i < list.size - 1; i ++) {
   list.add(null);
}
list.add(yourObject);
0

, List<Double>. , Map<Integer,Double> , .

, , .

Is the data structure ultimately completely populated or is data rare?

0
source

what other people said about securityCapacity () ...

you should write a class like DynamicArrayList that extends ArrayList. then just override add (n, x) to do this for the specified add (null) loop logic.

0
source

All Articles