aspose file tools
The moose likes Beginning Java and the fly likes The following method generates an OutOfMemoryError, how to overcome that? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "The following method generates an OutOfMemoryError, how to overcome that?" Watch "The following method generates an OutOfMemoryError, how to overcome that?" New topic
Author

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

Varuna Seneviratna
Ranch Hand

Joined: Jan 15, 2007
Posts: 164
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.

>


Varuna Seneviratna
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24061
    
  13

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)];


[Jess in Action][AskingGoodQuestions]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32712
    
    4
Have you read what the nextInt() method returns, and what the maximum size of your List would be?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32712
    
    4
I see Ernest has beaten me to it!
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
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

Joined: Jul 08, 2003
Posts: 24061
    
  13

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

Joined: Nov 07, 2008
Posts: 488
Fred, you beat me to nitpicking this as well

SCJA
~Currently preparing for SCJP6
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
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
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: The following method generates an OutOfMemoryError, how to overcome that?
 
Similar Threads
Why does this method works without a return statement outside while loop?
2D Boolean array and randomness
Arrays again :-(
randomly picking numbers