It's not a secret anymore!*
The moose likes Beginning Java and the fly likes Array Maximum Size? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array Maximum Size?" Watch "Array Maximum Size?" New topic
Author

Array Maximum Size?

Sam Bluesman
Ranch Hand

Joined: Nov 21, 2004
Posts: 191
Hi.

Does anyone know if java places a maximum on the number of elements an array can potentially have?

Thanks
[ June 02, 2007: Message edited by: Sam Bluesman ]

Moosey knows best
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11160
    
  16

see here


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18531
    
  40

Hmmmm... using the example, in the topic, that Fred referenced. It looks like there is a (slightly below) 2 gigabyte size limit for integer arrays.

For example, when I try this...


int[] j = new int[Integer.MAX_VALUE/4];


I get an out of memory condition. However, when I do this...



It works fine, even though this second case allocates more memory.

BTW, I used a "-Xmx20g" switch for the heap, so the out of memory condition is not due to the heap size.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Pravin Jain
Ranch Hand

Joined: May 20, 2007
Posts: 60
BTW there are switches when you start java to specify thay you need more
memory. eg. java -Xms<size> <main-class>


The Zen of Java Programming.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18531
    
  40

After playing around for a bit, it looks like the maximum array size is slightly less than 2 gigabytes -- for all array types. I can have almost twice as many elements of shorts than ints, twice as many elements of bytes than shorts, etc.

I don't have the exact number for elements, but it's close enough. And again, I used a very large heap, so the out of memory condition is not an out of heap memory condition.

Henry
 
jQuery in Action, 2nd edition
 
subject: Array Maximum Size?
 
Similar Threads
second maximum value from the array
Arrays.binarySearch() query
max value of an array
Dim of Array
size of array