Cemre Mengü
Cemre Mengü

Reputation: 18764

Initial size for the ArrayList

You can set the initial size for an ArrayList by doing

ArrayList<Integer> arr=new ArrayList<Integer>(10);

However, you can't do

arr.add(5, 10);

because it causes an out of bounds exception.

What is the use of setting an initial size if you can't access the space you allocated?

The add function is defined as add(int index, Object element) so I am not adding to index 10.

Upvotes: 362

Views: 708687

Answers (18)

Tajdin Gurdal
Tajdin Gurdal

Reputation: 1

The best way is this:

EvictingQueue<Integer> ignitionOnOdometer = EvictingQueue.create(size);

Upvotes: 0

Wasit Shafi
Wasit Shafi

Reputation: 1599

The argument we pass say N to constructor is the capacity of memory reserved for N elements, not the size of the array list i.e the no of elements, for more info can refer to official docs: ArrayList constructor.

But still what you was to achieve can be easily done with little changes in the code by assigning N elements with some default value initially and the instead of using add() use set() method to update the values

import java.util.*;

class Scratch {
  public static void main(String[] args) {
    int DEFAULT_INT_VALUE = 0;

    // set first 10 elements with default value 0
    List<Integer> arr = new ArrayList<Integer>(Collections.nCopies(10, DEFAULT_INT_VALUE));

    // why to use set(5, 10) instead of add(5, 10)..? simply because add() will insert new element at index 5, which here actually we just to modify the 5 index element in array list
    arr.set(5, 10);

    // output: arr= [0, 0, 0, 0, 0, 10, 0, 0, 0, 0]
    System.out.println("arr= " + arr.toString());
  }
}

Upvotes: 1

pattern cutter
pattern cutter

Reputation: 1

contrib..

List <Destination\> destinations = Collections.nCopies(source.size(), Destination.class.newInstance());

Upvotes: 0

anch2150
anch2150

Reputation: 81

My two cents on Stream. I think it's better to use

IntStream.generate(i -> MyClass.contruct())
         .limit(INT_SIZE)
         .collect(Collectors.toList());

with the flexibility to put any initial values.

Upvotes: 1

H.T. Koo
H.T. Koo

Reputation: 140

Being late to this, but after Java 8, I personally find this following approach with the Stream API more concise and can be an alternative to the accepted answer.

For example,

Arrays.stream(new int[size]).boxed().collect(Collectors.toList())

where size is the desired List size and without the disadvantage mentioned here, all elements in the List are initialized as 0.

(I did a quick search and did not see stream in any answers posted - feel free to let me know if this answer is redundant and I can remove it)

Upvotes: 7

unk
unk

Reputation: 129

I faced with the similar issue, and just knowing the arrayList is a resizable-array implementation of the List interface, I also expect you can add element to any point, but at least have the option to define the initial size. Anyway, you can create an array first and convert that to a list like:

  int index = 5;
  int size = 10;

  Integer[] array = new Integer[size];
  array[index] = value;
  ...
  List<Integer> list = Arrays.asList(array);

or

  List<Integer> list = Arrays.asList(new Integer[size]);
  list.set(index, value);

Upvotes: 4

Hrishikesh Kadam
Hrishikesh Kadam

Reputation: 37372

This might help someone -

ArrayList<Integer> integerArrayList = new ArrayList<>(Arrays.asList(new Integer[10]));

Upvotes: 7

Farzan.s
Farzan.s

Reputation: 945

if you want to use Collections.fill(list, obj); in order to fill the list with a repeated object alternatively you can use

ArrayList<Integer> arr=new ArrayList<Integer>(Collections.nCopies(10, 0));

the line copies 10 times 0 in to your ArrayList

Upvotes: 69

Natix
Natix

Reputation: 14257

Capacity of an ArrayList isn't the same as its size. Size is equal to the number of elements contained in the ArrayList (and any other List implementation).

The capacity is just the length of the underlying array which is used to internaly store the elements of the ArrayList, and is always greater or equal to the size of the list.

When calling set(index, element) on the list, the index relates to the actual number of the list elements (=size) (which is zero in your code, therefore the AIOOBE is thrown), not to the array length (=capacity) (which is an implementation detail specific to the ArrayList).

The set method is common to all List implementations, such as LinkedList, which isn't actually implemented by an array, but as a linked chain of entries.

Edit: You actually use the add(index, element) method, not set(index, element), but the principle is the same here.

Upvotes: 24

sambhu
sambhu

Reputation: 121

ArrayList myList = new ArrayList(10);

//  myList.add(3, "DDD");
//  myList.add(9, "III");
    myList.add(0, "AAA");
    myList.add(1, "BBB");

    for(String item:myList){
        System.out.println("inside list : "+item);
    }

/*Declare the initial capasity of arraylist is nothing but saving shifting time in internally; when we add the element internally it check the capasity to increase the capasity, you could add the element at 0 index initially then 1 and so on. */

Upvotes: 0

panther
panther

Reputation: 21

If you want to add 10 items to your ArrayList you may try that:

for (int i = 0; i < 10; i++)
    arr.add(i);

If you have already declare an array size variable you would use the variable size instead of number '10'

Upvotes: 1

Gert Jan Schoneveld
Gert Jan Schoneveld

Reputation: 1787

If you want a list with a predefined size you can also use:

List<Integer> arr = Arrays.asList(new Integer[10]);

Upvotes: 167

user3692587
user3692587

Reputation: 101

If you want to add the elements with index, you could instead use an array.

    String [] test = new String[length];
    test[0] = "add";

Upvotes: 10

roll1987
roll1987

Reputation: 183

Although your arraylist has a capacity of 10, the real list has no elements here. The add method is used to insert a element to the real list. Since it has no elements, you can't insert an element to the index of 5.

Upvotes: 1

NPE
NPE

Reputation: 500893

You're confusing the size of the array list with its capacity:

  • the size is the number of elements in the list;
  • the capacity is how many elements the list can potentially accommodate without reallocating its internal structures.

When you call new ArrayList<Integer>(10), you are setting the list's initial capacity, not its size. In other words, when constructed in this manner, the array list starts its life empty.

One way to add ten elements to the array list is by using a loop:

for (int i = 0; i < 10; i++) {
  arr.add(0);
}

Having done this, you can now modify elements at indices 0..9.

Upvotes: 511

quaylar
quaylar

Reputation: 2635

I guess an exact answer to your question would be:

Setting an intial size on an ArrayList reduces the nr. of times internal memory re-allocation has to occur. The list is backed by an array. If you specify i.e. initial capacity 0, already at the first insertion of an element the internal array would have to be resized. If you have an approximate idea of how many elements your list would hold, setting the initial capacity would reduce the nr. of memory re-allocations happening while you use the list.

Upvotes: 6

Hunter McMillen
Hunter McMillen

Reputation: 61540

Right now there are no elements in your list so you cannot add to index 5 of the list when it does not exist. You are confusing the capacity of the list with its current size.

Just call:

arr.add(10)

to add the Integer to your ArrayList

Upvotes: 3

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

10 is the initial capacity of the AL, not the size (which is 0). You should mention the initial capacity to some high value when you are going to have a lots of elements, because it avoids the overhead of expanding the capacity as you keep adding elements.

Upvotes: 10

Related Questions