Reputation: 329
I have an ArrayList:
List<Integer> array = new ArrayList<Integer>(M);
At some point in my code I add a new integer value at this array list at a specific index:
array.add(index, value);
The documentation says for that method:
Inserts the specified element at the specified position in this list (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
and that's fine because that is what I actually want to do. The problem is that any time I do this, the size of my array grows by 1. That is, initially I had an array with size M filled in with zeroes. When I add the first value at index 0, I have this value there and M zero values, resulting in an array of size M + 1. When I add the second value at index 0, I have this value at index 0, the previous value shifted to the right at index 1, and M zero values, resulting in an array of size M + 2 etc.
My question is, how to add an element at a specific index of my arraylist (in my case, at index 0) shifting the previous elements by 1 index without exceeding the predefined capacity of the arraylist?
(I have to say, ArrayList is one of the most common structures in Java and yet one of the most confusing for me ...)
EDIT: I have to note that initially I fill in my arraylist with M zero values using a for loop, therefore I have e.g. for M = 5 an arraylist like this. [0, 0, 0, 0, 0]
Upvotes: 1
Views: 2878
Reputation: 21
You must use set method instead of add methods i.e. array.set(index, value);
.
Upvotes: 0
Reputation: 11
When you want to add values at a specific index in arraylist without increasing its length , it is better to use set method from arraylist. Use ArrayList.set(int index, E element)
Upvotes: 1
Reputation: 136022
You can remove the last element of the list and then insert. This will keep size unchanged
Upvotes: 1