This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Arraylist sublist indexoutofboundsexcpetion  RSS feed

 
p mayur
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to show the first 5 items of an arraylist. when the list is 5 or above it works fine. if its below 5 then i get indexoutofboundsexcpetion.
How to check that? Please help me.

                  
      
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So how many values are you passing via the intent? 5?
 
p mayur
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
many values. it will show the top 5 and if i remove one item from list then the next one will be adde at the bottom
 
Norm Radder
Ranch Foreman
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to check that?
The arrayList class has a method that returns the length of the list. Use that to check if the list has 5 elements.
What should the code do if there are less than 5 elements?  Return the actual number of elements or pad the list to make 5?
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmm.
Why don't you check what is actually the size of your fNameTemp and lNameTemp after they are populated.

Also keep in mind
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
 
Liutauras Vilda
Marshal
Posts: 4650
318
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
p mayur wrote:when the list is 5 or above it works fine. if its below 5 then i get indexoutofboundsexcpetion.

That is expected looking at the code and explicitly specified indexes.

How about if you'd create some extra methods? Like listHasAtLeastFiveElements(), the other maybe printFirstFiveElements() and printAllElements() (or something else needed instead printing). Having such methods name, intention would become clear where the things go wrong.
 
Liutauras Vilda
Marshal
Posts: 4650
318
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aren't those 10 lines of code supposed to be in another method or two. Currently it looks that those 10 lines do more than one thing.

Pay attention to your formatting. It is all over the place, but that is probably because you use spaces and tabs in order to indent your code.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!