how does an ArrayList compare to a dynamic array

2020-04-07 19:05发布

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?

in that case they would be the same thing !

presumably they are the same thing?

5条回答
相关推荐>>
2楼-- · 2020-04-07 19:29

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?.

查看更多
来,给爷笑一个
3楼-- · 2020-04-07 19:33

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.

查看更多
▲ chillily
4楼-- · 2020-04-07 19:44

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.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-04-07 19:52

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.

查看更多
男人必须洒脱
6楼-- · 2020-04-07 19:54

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.

查看更多
登录 后发表回答