• Post Reply Bookmark Topic Watch Topic
  • New Topic

Populating the list from elements of another list  RSS feed

 
Kunal Lakhani
Ranch Hand
Posts: 622
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a list, named numbers, which is populated twice (returned from some method). I need to store it in another list named total
This is the code i am running



The above code is present in a method which executes twice.

First time the number is returned as 1,6, which is placed in index 0,1 of total. But next time, when again 2 numbers is returned(say, 1, 9),(and i need it to be placed in index 2,3) and my for loop runs, it gives the following
exception : java.lang.IndexOutOfBoundsException: Index: 2, Size: 0
 
Kunal Lakhani
Ranch Hand
Posts: 622
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Solved. That was simple, i messed it up.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. Never use get(i) to iterate a List. Use a foreach loop or an explicit Iterator. That way the iteration code will work with any Collection, and should perform consistently for any Collection (or at least perform as well as an iteration can for that particular Collection).

2. The Collection interface specifies an addAll() method, so you can just call list2.addAll(list1);

3. As far as I know, all the Collections in the core API have a constructor that takes another Collection as an argument, so you could do, for instance, list2 = new ArrayList(list1);

As a general rule, when you're looking to do something like this, you should assume you're not the first one to do it, and you should look at the javadocs to see if there's already a facility for doing it.
 
Kunal Lakhani
Ranch Hand
Posts: 622
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jeff Verdegan
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!