8

Is an ArrayList is just the interface for a dynamic array? Or are they the same thing?

like: ArrayList corresponds to dynamic array, HashMap corresponds to Map ?

except I don't see any Java API for something like a dynamic array, unless it is ArrayList?

Islam Hassan
  • 673
  • 1
  • 10
  • 21
bezzoon
  • 1,755
  • 4
  • 24
  • 52
  • 1
    "like: ArrayList corresponds to Map, dynamic array corresponds to HashMap?" No, neither parts of that make any real sense; maps and arrays are two separate data structures. – Dennis Meng Nov 07 '13 at 18:18

5 Answers5

5

Yes. In short.

A longer explanation is that an ArrayList is a collection that uses arrays for storage, rather than a linked list, doubly linked list or similar. This means that it gives all the benefits of using an Array, whilst Java looks after the mechanics of sizing the Array for you (dynamically).

I seem to remember that the initial array is created with a default maximum size (which can be specified by the user). Should the collection run out of space, then a larger array is created and the contents of the original array copied into the new one. The increment in size is set to prevent this happening too often, as the operation is fairly costly.

Java also offers the Vector collection which is similar, but is also thread safe, see: What are the differences between ArrayList and Vector?.

Community
  • 1
  • 1
Henry Florence
  • 2,848
  • 19
  • 16
2

ArrayList is the resizable-array implementation of the List interface.
So that's probably what you are looking for if you need a dynamic array.

Iulian Rosca
  • 1,005
  • 4
  • 15
  • 30
2

ArrayList is not a dynamic array, it's not an array type dynamic or not, it's just one of the implementations of the List interface. Understand the difference between classes and interfaces. On the other hand arrays are container objects with the fixed size.

  • There's a difference between the abstract data type "dynamic array" and the weird generic built-in type `T[]` ("array of `T`"). –  Nov 07 '13 at 18:40
1

If in the dynamic sense you mean an array which can change in size then a List is an interface for a dynamic array. It is named ArrayList because it uses an array internally that's all.

Your analogy does not fit in the java collections framework since you can say that an ArrayList is a dynamic array but Map (or HashMap for that matter) does not have a "primitive" counterpart.

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
1

If by 'dynamic array' you mean an array in C++, then all arrays in Java are dynamic and stored on heap. ArrayList is a resizable wrapper for it. It also provides simple consistency checks - i.e. that you don't modify your array from outside during iteration.

Andrey Chaschev
  • 16,160
  • 5
  • 51
  • 68