tags:

views:

111

answers:

1

Hi

From looking at the Java Collections API i see that arrays are not regarded as collections. If not what are arrays regarded as?

+10  A: 

Arrays are "special" in Java - they don't implement any interfaces, which means they can't implement the collection interfaces. They're collections in "natural language" terms, and you can use the enhanced for loop over them - but if you want to use an array within the collection API, you'll need something like Arrays.asList which wraps an array with the List<T> interface. (The result is only a view on the array - changes to the array are visible through the list, and vice versa.)

(This is in contrast to .NET, where T[] implements IList<T> etc.)

Jon Skeet
Thanks Jon, thats a nice helpful answer. Its something i never really thought about before, but im preparing a presentation on some collection topics. I want to be prepared if and when i get asked about arrays. Thanks Jon
Note that you can change elements through the List, but you cannot add new elements to it, because the backing array cannot grow. You'll get a runtime error if you try.
FredOverflow