This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Customer Requirements for Developers and have Marcho Behler 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 Customer Requirements for Developers this week in the Jobs Discussion 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: 19936
    
  44

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: 20049
    
  30

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 - OCEJPAD 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()
 
It's not a secret anymore!