seeker
seeker

Reputation: 6991

What is algorithmic cost of adding, accessing or removing an element from an ArrayList in Java

I have a web application that uses ArrayList's extensively to store and operate on data within itself. However,recently I understood that HashMap's may have been a better choice. Could anyone tell me what exactly is the algorithmic cost(Big O(n)) of adding, accessing and removing an element from both and whether it is wise to go into the code and change them for the sake of efficency?

Upvotes: 0

Views: 184

Answers (3)

user799188
user799188

Reputation: 14415

Please have a look at http://www.coderfriendly.com/wp-content/uploads/2009/05/java_collections_v2.pdf

  • O(1) to get/add
  • O(n) for contains
  • O(1) for next

Upvotes: 1

user130076
user130076

Reputation:

The documentation for ArrayList has a discussion of the performance of the performance of these operations. As for HashMap, it will be O(1) for all three. This does assume, however, that your hashCode method is well-implemented, and is also O(1).

Upvotes: 1

pcalcao
pcalcao

Reputation: 15990

For ArrayList:

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

From the documentation: http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

For HashMap:

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

From the documentation: http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

Upvotes: 8

Related Questions