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.