Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The time complexity of Iterator() in java

Tags:

java

iterator

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?

Thanks

like image 296
Aaron Avatar asked Jul 08 '26 20:07

Aaron


1 Answers

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)

like image 61
kjsebastian Avatar answered Jul 11 '26 12:07

kjsebastian