1

We have an operation as such:

animal[i] = animal[i+1]

when using an array in java. But I'm confused on how Array List works in Java and I'm wondering, what is the equivalent operation for an Array List as of above?

Would it be something like:

animal.get(i) = animal.get(i+1) ?

I'm getting an error saying "the left side must be a variable" if i do so, so i assume I'm doing it wrong?

clink
  • 213
  • 3
  • 11
  • The api docs for arraylist show accessors. To add an item a specific location in the list, use the appropriate add method. Because arraylist is a class, and impls of it are objects you generally can't just use operators line you are doing. –  May 09 '18 at 12:26
  • perhaps nothing to do with your question about assignment.... I would remove the 1st element, and copy and append the last element, instead of looping through the list. – Kent May 09 '18 at 12:26

1 Answers1

1

animal.get(i) is a value returned by a method. It can be assigned to a variable, but you cannot assign anything to it.

You have a set method in order to replace the value of the i'th element of a List:

animal.set(i,animal.get(i+1));
Eran
  • 387,369
  • 54
  • 702
  • 768
  • i see. So i assume another example, animal[numberOfAnimals] = animalToAdd it would be just animal.add(animalToAdd)? – clink May 09 '18 at 12:30
  • @clink yes. in that case using an ArrayList is easier compared to using an array, since it is automatically resized when necessary. – Eran May 09 '18 at 12:31