ArrayList(int initialCapacity)
and other collections in java work on int index.
Can’t there be cases where int is not enough and there might be need for more than range of int?
UPDATE:
Java 10 or some other version would have to develop new Collection framework for this. As using long with present Collections would break the backward compatibility. Isn’t it?
There can be in theory, but at present such large arrays (arrays with indexes outside the range of an integer) aren’t supported by the JVM, and thus ArrayList doesn’t support this either.
Is there a need for it? This isn’t part of the question per-se, but seems to come up a lot so I’ll address it anyway. The short answer is in most situations, no, but in certain ones, yes. The upper value of an
intin Java is2,147,483,647, a tad over 2 billion. If this were an array of bytes we were talking about, that puts the upper limit at slightly over 2GB in terms of the amount of bytes we can store in an array. Back when Java was conceived and it wasn’t unusal for a typical machine to have a thousand times less memory than that, it clearly wasn’t too much of an issue – but now even a low end (desktop/laptop) machine has more memory than that, let alone a big server, so clearly it’s no longer a limitation that no-one can ever reach. (Yes, we could pack the bytes into a wrapper object and make an array of those, but that’s not the point we’re addressing here.) If we switch to thelongdata type, then that pushes the upper limit of a byte array to well over 9.2 Exabytes (over 9 billion GB.) That puts us firmly back into “we don’t need to sensibly worry about that limit” territory for at least the foreseeable future.So, is Java making this change? One of the plans for Java 10 is due to tackle “big data” which may well include support for arrays with
longbased indexes. Obviously this is a long way off, but Oracle is at least thinking about it:You could theoretically work around this limitation by using your own collection classes which used multiple arrays to store their data, thus bypassing the implicit limit of an
int– so it is somewhat possible if you really need this functionality now, just rather messy at present.In terms of backwards compatibility if this feature comes in? Well you obviously couldn’t just change all the
ints tolongs, there would need to be some more boilerplate there and, depending on implementation choices, perhaps even new collection types for these large collections (considering I doubt they’d find their way into most Java code, this may well be the best option.) Regardless, the point is that while backwards compatibility is of course a concern, there are a number of potential ways around this so it’s not a show stopper by any stretch of the imagination.