Language: Java
when creating a method to add to the front of the arraylist, I have the following:
public void addToFront(T data) {
if (data == null) {
throw new
IllegalArgumentException("Data here is null");
}
for (int i = size; i > 0; i--) {
backingArray[i] = backingArray[i
-1];
}
size++;
}
I was wondering what the bold part of this code means.
Thanks!
for (int i = size; i > 0; i--) { backingArray[i] = backingArray[i -1]; } size++; This means moving the content of array backingArray to one location right to make the front of the array available to insert new element. And then it increments the size by 1. Example: If the array looks like
4 | 6 | 3 | 7 | 8 |
After the above block execution it looks like
4 | 6 | 3 | 7 | 8 |
Means all the elements are shifted to one location right to make first location available.
Get Answers For Free
Most questions answered within 1 hours.