D
D
Domus2017-04-15 15:23:50
Java
Domus, 2017-04-15 15:23:50

While or Iterator?

Good afternoon!
What construction is preferable to use for iteration of elements? I understand that the compiler converts "for each" into an Iterator construct and therefore reduces speed, but what if it's better to stick to the more pleasing "for each" construct?

HashSet<Integer> oneHash = new HashSet<>();

                // First way
    for(Integer element : oneHash){
      System.out.println(element);
    }

                // Second way
    Iterator<Integer> it = oneHash.iterator();
    while(it.hasNext()){
      System.out.println(it.next());
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
protven, 2017-04-15
@Domus

What java? If the eighth, then why not use the stream api ?
And believe me, in such things you should not bother about "speed". It is better to focus on the readability of the code. Naturally. 99.9% of the bottlenecks in any more or less useful system are reading from the database, transferring data over the network, reading / writing to disk. If your bottleneck is an iteration over standard Javai collections and you need to optimize this place, then you either have a spherical example in a vacuum, and not an applied system, or everything is so cool that you can only envy.

E
Evgeny Kolman, 2017-04-15
@Evgeny_13

It is more convenient to use the second option if you are passing primitive types and their reference types, but if you are passing an object you created - the first way. (IMHO)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question