What is the maximum size of HashSet, Vector, LinkedList? I know that ArrayList can store more than 3277000 numbers.
However the size of list depends on the memory (heap) size. If it reaches maximum the JDK throws an OutOfMemoryError.
But I don’t know the limit for the number of elements in HashSet, Vector and LinkedList.
There is no specified maximum size of these structures.
The actual practical size limit is probably somewhere in the region of
Integer.MAX_VALUE(i.e. 2147483647, roughly 2 billion elements), as that’s the maximum size of an array in Java.HashSetuses aHashMapinternally, so it has the same maximum size as thatHashMapuses an array which always has a size that is a power of two, so it can be at most 230 = 1073741824 elements big (since the next power of two is bigger thanInteger.MAX_VALUE).HashMapstops resizing, then it will still allow you to add elements, exploiting the fact that each bucket is managed via a linked list. Therefore the only limit for elements in aHashMap/HashSetis memory.Vectoruses an array internally which has a maximum size of exactlyInteger.MAX_VALUE, so it can’t support more than that many elementsLinkedListdoesn’t use an array as the underlying storage, so that doesn’t limit the size. It uses a classical doubly linked list structure with no inherent limit, so its size is only bounded by the available memory. Note that aLinkedListwill report the size wrongly if it is bigger thanInteger.MAX_VALUE, because it uses aintfield to store the size and the return type ofsize()isintas well.Note that while the
CollectionAPI does define how aCollectionwith more thanInteger.MAX_VALUEelements should behave. Most importantly it states this thesize()documentation:Note that while
HashMap,HashSetandLinkedListseem to support more thanInteger.MAX_VALUEelements, none of those implement thesize()method in this way (i.e. they simply let the internalsizefield overflow).This leads me to believe that other operations also aren’t well-defined in this condition.
So I’d say it’s safe to use those general-purpose collections with up to
Integer.MAX_VLAUEelements. If you know that you’ll need to store more than that, then you should switch to dedicated collection implementations that actually support this.