This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 Murach's Java Servlets and JSP this week in the Servlets 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: 18509
    
  40

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: 19651
    
  18

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Time Complexity of HashMap.toArray()
 
Similar Threads
Scriptlets -> Time and Space Complexity
Good book to understand the Analysis and Design of Algorithm
How long did it take you to get "good" at Java?
interview question
O(n) of string.length()