简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM