permaculture playing cards*
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
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: 18760
    
  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: 19680
    
  19

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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Time Complexity of HashMap.toArray()