• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array Index Out Of Bounds Exception

 
Amy Lee
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I created the following constructer to create a deck of 52 cards, but when I call the method it gives an out of bounds exception. Since my variable ais an ArrayList, I thought that the array would resize each time I added to it. The cursor is positioning itself at a.addwhen it throws the exception. Here is my code - any help would be appreciated; thanks!

 
Amy Lee
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Never mind, I just figured it out - there was a typo in my for loop; THANKS ANYWAY! :-)
 
Eric Weinberg
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ArrayList does resize. check out the java API for more info on it.

*warning* personal speculation with a vauge sence of whats going on to follow:


But I think your chasing a red herring. I would probably say that its not the array list, but yuor string arrays that are going out of bounds. Check it out when you do your trace.
I think your problem might be comming from ++j & ++i ...personaly i can't figure out the difference between J++ and ++J ....yes i know there is a difference and it has to do when it's actually added. So generally i avoid them as much as possible so yeah.... try doing your loops to for(int i=0;i<whatever;i++)
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem (as I imagine Amy figured out) is that she's defined i as ranging up to the length of mySuits, and j of myValues, but is then using j to index mySuits, and i to index myValues.

Regarding ++j vs. j++ in a "for" loop: either one will work, but one imagines that ++j is a little bit more efficient -- it is in C, at least. ++j increments the variable, and returns the incremented value, whereas j++ stores the old value, increments the variable, and then returns the stored value -- a more complex process which takes a bit longer to do. Since in the case of a "for" loop we don't even use the return value, it doesn't matter which one we should use, so why not use the more efficient one?
 
Eric Weinberg
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
good explination!

thanks, hmm well why wouldn't i use the more eficent one. Probably because it's new and different and scares me. Okay not new, and different only to me it would seem. thanks for that morsal of information, I'll haveto look into that!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic