Aaron Aaron - 1 year ago 106
Java Question

The time complexity of Iterator() in java

I am new to Java. I have a question about the time complexity of java iterator().

Set<Integer> set = new HashSet<>();

Iterator<Integer> iter = set.iterator(); ==> (2)

I wanna know what is the time complexity of step 2? It is const time O(1) or it depends on the size of set?


Answer Source

Calling iterator() is constant time. It is a method call that returns an Iterator instance on the collection you are calling on. Actually iterating through the collection using the iterator using while (hasNext()) will be O(n)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download