Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Maximum Size that an Array can hold?

Tags:

arrays

c#

In C# 2008, what is the Maximum Size that an Array can hold?

like image 200
DNR Avatar asked Sep 08 '09 02:09

DNR


People also ask

Do arrays have a limit?

A Java program can only allocate an array up to a certain size. It generally depends on the JVM that we're using and the platform. Since the index of the array is int, the approximate index value can be 2^31 – 1. Based on this approximation, we can say that the array can theoretically hold 2,147,483,647 elements.

What is the maximum array size in Java?

The 32-bit Java int can go to a maximum of 2,147,483,647, so that is the theoretical maximum Java array size. However, virtual machines for different operating systems may not allocate every available bit to the elements in the Java array.


1 Answers

System.Int32.MaxValue 

Assuming you mean System.Array, ie. any normally defined array (int[], etc). This is the maximum number of values the array can hold. The size of each value is only limited by the amount of memory or virtual memory available to hold them.

This limit is enforced because System.Array uses an Int32 as it's indexer, hence only valid values for an Int32 can be used. On top of this, only positive values (ie, >= 0) may be used. This means the absolute maximum upper bound on the size of an array is the absolute maximum upper bound on values for an Int32, which is available in Int32.MaxValue and is equivalent to 2^31, or roughly 2 billion.

On a completely different note, if you're worrying about this, it's likely you're using alot of data, either correctly or incorrectly. In this case, I'd look into using a List<T> instead of an array, so that you are only using as much memory as needed. Infact, I'd recommend using a List<T> or another of the generic collection types all the time. This means that only as much memory as you are actually using will be allocated, but you can use it like you would a normal array.

The other collection of note is Dictionary<int, T> which you can use like a normal array too, but will only be populated sparsely. For instance, in the following code, only one element will be created, instead of the 1000 that an array would create:

Dictionary<int, string> foo = new Dictionary<int, string>(); foo[1000] = "Hello world!"; Console.WriteLine(foo[1000]); 

Using Dictionary also lets you control the type of the indexer, and allows you to use negative values. For the absolute maximal sized sparse array you could use a Dictionary<ulong, T>, which will provide more potential elements than you could possible think about.

like image 139
Matthew Scharley Avatar answered Oct 14 '22 12:10

Matthew Scharley