aspose file tools*
The moose likes Java in General and the fly likes Time Complexity of HashMap.toArray() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Time Complexity of HashMap.toArray()" Watch "Time Complexity of HashMap.toArray()" New topic
Author

Time Complexity of HashMap.toArray()

Mike Broadbear
Ranch Hand

Joined: Jan 14, 2002
Posts: 39
I was wondering if anyone knows the time complexity of a HashMap.toArray() operation.

...Mike B.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18101
    
  39

First, I am assuming that you mean get a Set first, as Maps don't have a toArray() method.

If memory serves, I believe it is just a simple loop with an iterator to fill an newly created array -- so it should be O(n).

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19538
    
  16

I don't think it can be done more efficiently. In the end, all elements need to be copied to the new array. While an ArrayList could possibly do it faster because it can use native code like System.arraycopy and perhaps even cloning its array, that still copies all elements.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
 
subject: Time Complexity of HashMap.toArray()
 
Similar Threads
How long did it take you to get "good" at Java?
interview question
O(n) of string.length()
Good book to understand the Analysis and Design of Algorithm
Scriptlets -> Time and Space Complexity