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 Elasticsearch in Action this week in the Big Data 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: 19334
    
  41

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: 19908
    
  23

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