Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

ArrayList get() method logic  RSS feed

 
Ashwin Raju
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I was writing code to switch 2 pairs of strings using arraylist. I finally got the program to run but I am not able to understand the way this get() method works.

l.add(i,l.get(i+1)) ---> This code should add the next element(i+i) to the previous index value(i) but it skips ahead(jumps to the 3rd index value instead of the 2nd) and does not print the desired answer.

ANSWER WHEN I RUN ABOVE CODE:
Enter a text value:
Hi how are you today
[are, Hi, today, are, today]

l.add(i,l.get(i)) ----> This code gets the next value(get(i)) and adds that to the previous index value. HOW IS THIS HAPPENING?

ANSWER WHEN I RUN ABOVE CODE:
Enter a text value:
Hi how are you today
[how, Hi, you, are, today] ---> this is the right answer FYI
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ashwin Raju wrote:l.add(i,l.get(i)) ----> This code gets the next value(get(i)) and adds that to the previous index value. HOW IS THIS HAPPENING?

Hi Ashwin, and welcome to javaRanch.

TBH, I'm not exactly sure why, because I would expect the code you posted to fail on the last element - but ONLY on the last one, because before that it should work just fine.

Take your example using i=0:
String temp = l.get(i); - temp == "how".
l.remove(i); - element 0 now == "Hi"
l.add(i, l.get(i)); - elements 0 AND 1 now equal "Hi"

And the reason is that the compiler evaluates the get(i) (in the above case get(0)) BEFORE it executes the add(); otherwise how would it know what to pass to the add() method?

And since add() inserts a NEW element at the specified position, you now have two elements with "Hi" in them.

HIH

Winston

PS: KeepItDown (←click). I'm sure you didn't mean to, but lots of all-caps and bolding comes across as SHOUTING!!! - and nobody likes being shouted at.
 
Campbell Ritchie
Marshal
Posts: 55681
162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lists are not specifically designed with swapping two elements in mind, so you need to think carefully about what you are doing. Have you come across the set method? If you have many pairs to swap set will be faster than remove and add.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!