• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

The following method generates an OutOfMemoryError, how to overcome that?

 
Varuna Seneviratna
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following method generates an OutOfMemoryError.How is it possible to generate a random integer which can be used as the number of elements of an ArrayList Or Array that won't generate an OutOfMemoryError.

>
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is here, of course:

int numberOfResponses=randomNumberGenerator.nextInt();

numberOfResponses can be negative (in which case the loop won't run at all!) or it can be an enormous number near Integer.MAX_VALUE (in which case randomList will grow large and you'll get an OutOfMemoryError.

In any case, all of this is unnecessary to the point of being silly. The answer is no more or less random than simply saying

return new String[] {"No", "Yes", "Maybe"}[randomNumberGenerator.nextInt(3)];

 
Campbell Ritchie
Sheriff
Pie
Posts: 49849
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you read what the nextInt() method returns, and what the maximum size of your List would be?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49849
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see Ernest has beaten me to it!
 
Fred Hamilton
Ranch Hand
Posts: 684
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for my own edification, is not the statement...

if(numberOfResponses > 0) {

redundant here? cause if numberOfResponses is 0 or negative, then the for condition causes the for block not to be executed even once?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fred Hamilton wrote:if numberOfResponses is 0 or negative, then the for condition causes the for block not to be executed even once?


ABsolutely right.
 
Brian Legg
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fred, you beat me to nitpicking this as well
 
Fred Hamilton
Ranch Hand
Posts: 684
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brian Legg wrote:Fred, you beat me to nitpicking this as well


OK my friend, I'll try try not to pick all the easy nits then
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic