Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what will happen to my ArrayList

I am trying to understand Java.

Let's assume I have an ArrayList of size 50 and pre-populated with some names.

Let's assume I remove 3rd and 4th element from the array list. What will happen to my array list? Will it get rearranged? Will it return null if I try to access the now-deleted 3rd and 4th elements?

like image 505
constantlearner Avatar asked Nov 27 '22 00:11

constantlearner


2 Answers

No, the elements after the one you are going to delete will be shifted to the left (expensive operation), so you won't have any hole.

As as side note: if you remove the 3rd element then the 5th element will be shifted to the left, so if afterwards you remove the 4th, you are instead removing the fifth of the starting collection. To remove two consecutive elements you should provide the same index twice.

like image 177
Jack Avatar answered Jan 01 '23 10:01

Jack


They will be rearranged and shifted.

If you want them to return null instead, just set those elements you want to remove to null explicitly rather than removing them.

like image 27
Michael Berry Avatar answered Jan 01 '23 10:01

Michael Berry