What is a difference between traditional loop and for-each loop? [duplicate]
up vote
10
down vote
favorite
This question already has an answer here:
How does the Java 'for each' loop work?
26 answers
I wonder if there is a difference between these:
ArrayList<Example> list = new ArrayList<Example>
1-)
for(int i = 0; i < list.size(); i++) {
list.get(i).doSomething();
}
2-)
for(Example example : list) {
example.doSomething();
}
If there is not any difference which one is more common or efficient?
java
marked as duplicate by Matsemann, Tunaki
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 7 '15 at 14:07
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
|
show 3 more comments
up vote
10
down vote
favorite
This question already has an answer here:
How does the Java 'for each' loop work?
26 answers
I wonder if there is a difference between these:
ArrayList<Example> list = new ArrayList<Example>
1-)
for(int i = 0; i < list.size(); i++) {
list.get(i).doSomething();
}
2-)
for(Example example : list) {
example.doSomething();
}
If there is not any difference which one is more common or efficient?
java
marked as duplicate by Matsemann, Tunaki
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 7 '15 at 14:07
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
Difference in what sense?
– Maroun
Nov 7 '15 at 11:13
Premature optimization: Don't. Just... Don't. If you don't have a speed problem, don't solve it. In 99,9% of all cases, you will not notice a difference between the two - except the obvious, with one you have an index (and no iterator) and it only works on methods with a get(x) method, while the other you have no index, an iterator and it works with any collection.
– Florian Schaetz
Nov 7 '15 at 11:14
The second one is more efficient. Because every .get(i) starts a random access search.
– Reinard
Nov 7 '15 at 11:14
@Reinard Potentially yes, depending on the list being iterated through. TheArrayList
in the example has no speed difference, but aLinkedList
would show noticeable differences.
– Kayaman
Nov 7 '15 at 11:17
2
@JaroslawPawlak You should always use a for-each loop, unless you need the index for some reason. (Or in Java 8, you can use streams.) And not because it's faster (it usually isn't) but because it's easier to read.
– biziclop
Nov 7 '15 at 12:06
|
show 3 more comments
up vote
10
down vote
favorite
up vote
10
down vote
favorite
This question already has an answer here:
How does the Java 'for each' loop work?
26 answers
I wonder if there is a difference between these:
ArrayList<Example> list = new ArrayList<Example>
1-)
for(int i = 0; i < list.size(); i++) {
list.get(i).doSomething();
}
2-)
for(Example example : list) {
example.doSomething();
}
If there is not any difference which one is more common or efficient?
java
This question already has an answer here:
How does the Java 'for each' loop work?
26 answers
I wonder if there is a difference between these:
ArrayList<Example> list = new ArrayList<Example>
1-)
for(int i = 0; i < list.size(); i++) {
list.get(i).doSomething();
}
2-)
for(Example example : list) {
example.doSomething();
}
If there is not any difference which one is more common or efficient?
This question already has an answer here:
How does the Java 'for each' loop work?
26 answers
java
java
edited Nov 7 '15 at 12:47
Jaroslaw Pawlak
4,49362149
4,49362149
asked Nov 7 '15 at 11:11
shanks
821216
821216
marked as duplicate by Matsemann, Tunaki
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 7 '15 at 14:07
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
marked as duplicate by Matsemann, Tunaki
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 7 '15 at 14:07
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
Difference in what sense?
– Maroun
Nov 7 '15 at 11:13
Premature optimization: Don't. Just... Don't. If you don't have a speed problem, don't solve it. In 99,9% of all cases, you will not notice a difference between the two - except the obvious, with one you have an index (and no iterator) and it only works on methods with a get(x) method, while the other you have no index, an iterator and it works with any collection.
– Florian Schaetz
Nov 7 '15 at 11:14
The second one is more efficient. Because every .get(i) starts a random access search.
– Reinard
Nov 7 '15 at 11:14
@Reinard Potentially yes, depending on the list being iterated through. TheArrayList
in the example has no speed difference, but aLinkedList
would show noticeable differences.
– Kayaman
Nov 7 '15 at 11:17
2
@JaroslawPawlak You should always use a for-each loop, unless you need the index for some reason. (Or in Java 8, you can use streams.) And not because it's faster (it usually isn't) but because it's easier to read.
– biziclop
Nov 7 '15 at 12:06
|
show 3 more comments
Difference in what sense?
– Maroun
Nov 7 '15 at 11:13
Premature optimization: Don't. Just... Don't. If you don't have a speed problem, don't solve it. In 99,9% of all cases, you will not notice a difference between the two - except the obvious, with one you have an index (and no iterator) and it only works on methods with a get(x) method, while the other you have no index, an iterator and it works with any collection.
– Florian Schaetz
Nov 7 '15 at 11:14
The second one is more efficient. Because every .get(i) starts a random access search.
– Reinard
Nov 7 '15 at 11:14
@Reinard Potentially yes, depending on the list being iterated through. TheArrayList
in the example has no speed difference, but aLinkedList
would show noticeable differences.
– Kayaman
Nov 7 '15 at 11:17
2
@JaroslawPawlak You should always use a for-each loop, unless you need the index for some reason. (Or in Java 8, you can use streams.) And not because it's faster (it usually isn't) but because it's easier to read.
– biziclop
Nov 7 '15 at 12:06
Difference in what sense?
– Maroun
Nov 7 '15 at 11:13
Difference in what sense?
– Maroun
Nov 7 '15 at 11:13
Premature optimization: Don't. Just... Don't. If you don't have a speed problem, don't solve it. In 99,9% of all cases, you will not notice a difference between the two - except the obvious, with one you have an index (and no iterator) and it only works on methods with a get(x) method, while the other you have no index, an iterator and it works with any collection.
– Florian Schaetz
Nov 7 '15 at 11:14
Premature optimization: Don't. Just... Don't. If you don't have a speed problem, don't solve it. In 99,9% of all cases, you will not notice a difference between the two - except the obvious, with one you have an index (and no iterator) and it only works on methods with a get(x) method, while the other you have no index, an iterator and it works with any collection.
– Florian Schaetz
Nov 7 '15 at 11:14
The second one is more efficient. Because every .get(i) starts a random access search.
– Reinard
Nov 7 '15 at 11:14
The second one is more efficient. Because every .get(i) starts a random access search.
– Reinard
Nov 7 '15 at 11:14
@Reinard Potentially yes, depending on the list being iterated through. The
ArrayList
in the example has no speed difference, but a LinkedList
would show noticeable differences.– Kayaman
Nov 7 '15 at 11:17
@Reinard Potentially yes, depending on the list being iterated through. The
ArrayList
in the example has no speed difference, but a LinkedList
would show noticeable differences.– Kayaman
Nov 7 '15 at 11:17
2
2
@JaroslawPawlak You should always use a for-each loop, unless you need the index for some reason. (Or in Java 8, you can use streams.) And not because it's faster (it usually isn't) but because it's easier to read.
– biziclop
Nov 7 '15 at 12:06
@JaroslawPawlak You should always use a for-each loop, unless you need the index for some reason. (Or in Java 8, you can use streams.) And not because it's faster (it usually isn't) but because it's easier to read.
– biziclop
Nov 7 '15 at 12:06
|
show 3 more comments
4 Answers
4
active
oldest
votes
up vote
19
down vote
accepted
Traditional loop
for (int i = 0; i < list.size(); i++) {
list.get(i).doSomething();
}
- allows to modify the list, e.g.:
- you can add extra element at the end of list and it will be also iterated through
- you know the index
- can be used to refer to another list of the same size
- can be used to refer to previous/next element
- efficient only in
RandomAccess
lists
- in case of
LinkedList
in every iteration of the loop,get(i)
will have to iterate over all elements starting fromhead/tail
toi
- in case of
- works only with
List
sinceList#get(int)
is used - error prone, a lot of things that can go wrong, e.g.:
i = 0;
instead ofint i = 0;
- will refer to variable declared before the loop, possible side effects outside of the loop
>
instead of<
- loop will not execute
j++
instead ofi++
- infinite loop
.get(j)
instead of.get(i)
- will always get the same element
For-each loop
for (Example example : list) {
example.doSomething();
}
- does not allow to modify the list
- trying to do so will most likely result in
ConcurrentModificationException
- trying to do so will most likely result in
- you don't know the index of the element
- you cannot refer to previous/next element
- efficient in all cases because uses
Iterator
specific for the collection
- efficient in case of
LinkedList
- efficient in case of
- works not only with every
Collection
, but with everyIterable
sinceIterable#iterator()
is used
- you can easily replace
List
with aSet
- no changes to the loop required - you can easily replace with your own class, it just has to implement
Iterable
- you can easily replace
- more robust (less code, fewer special characters)
Summary
for-each
loop wins with a score 3 : 2.
The only reason to use a traditional loop is when:
- the index of element is required, or
- the list has to be modified
add a comment |
up vote
3
down vote
They are basically the same, but for-each (the second one) has certain restrictions.
It can be used for accessing the array elements but not for modifying them.
It is not usable for loops that must iterate over
multiple collections in parallel—for example, to compare the elements of two arrays.It can be used only for a single element access and cannot be used to compare successive elements in an array. It is a forward-only iterator. If you want to access only a few elements of the array, you would need to use the traditional for loop.
@Point 1: you can modify the array elements by calling mutable methods. (or you need to specify, what you mean with "modify") I guess what you mean is that one cannot modify the array (orIterable
) itself.
– Tom
Nov 7 '15 at 11:28
add a comment |
up vote
1
down vote
The second one works with every type of (potentially unordered) Iterable, as it doesn't rely on random access, i.e. get(i)
.
add a comment |
up vote
1
down vote
for(:)
statement is a read-only loop. You cannot change a collection within this loop. Also you cannot use more than one element.
The traditional for
statement doesn't have such limits.
add a comment |
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
19
down vote
accepted
Traditional loop
for (int i = 0; i < list.size(); i++) {
list.get(i).doSomething();
}
- allows to modify the list, e.g.:
- you can add extra element at the end of list and it will be also iterated through
- you know the index
- can be used to refer to another list of the same size
- can be used to refer to previous/next element
- efficient only in
RandomAccess
lists
- in case of
LinkedList
in every iteration of the loop,get(i)
will have to iterate over all elements starting fromhead/tail
toi
- in case of
- works only with
List
sinceList#get(int)
is used - error prone, a lot of things that can go wrong, e.g.:
i = 0;
instead ofint i = 0;
- will refer to variable declared before the loop, possible side effects outside of the loop
>
instead of<
- loop will not execute
j++
instead ofi++
- infinite loop
.get(j)
instead of.get(i)
- will always get the same element
For-each loop
for (Example example : list) {
example.doSomething();
}
- does not allow to modify the list
- trying to do so will most likely result in
ConcurrentModificationException
- trying to do so will most likely result in
- you don't know the index of the element
- you cannot refer to previous/next element
- efficient in all cases because uses
Iterator
specific for the collection
- efficient in case of
LinkedList
- efficient in case of
- works not only with every
Collection
, but with everyIterable
sinceIterable#iterator()
is used
- you can easily replace
List
with aSet
- no changes to the loop required - you can easily replace with your own class, it just has to implement
Iterable
- you can easily replace
- more robust (less code, fewer special characters)
Summary
for-each
loop wins with a score 3 : 2.
The only reason to use a traditional loop is when:
- the index of element is required, or
- the list has to be modified
add a comment |
up vote
19
down vote
accepted
Traditional loop
for (int i = 0; i < list.size(); i++) {
list.get(i).doSomething();
}
- allows to modify the list, e.g.:
- you can add extra element at the end of list and it will be also iterated through
- you know the index
- can be used to refer to another list of the same size
- can be used to refer to previous/next element
- efficient only in
RandomAccess
lists
- in case of
LinkedList
in every iteration of the loop,get(i)
will have to iterate over all elements starting fromhead/tail
toi
- in case of
- works only with
List
sinceList#get(int)
is used - error prone, a lot of things that can go wrong, e.g.:
i = 0;
instead ofint i = 0;
- will refer to variable declared before the loop, possible side effects outside of the loop
>
instead of<
- loop will not execute
j++
instead ofi++
- infinite loop
.get(j)
instead of.get(i)
- will always get the same element
For-each loop
for (Example example : list) {
example.doSomething();
}
- does not allow to modify the list
- trying to do so will most likely result in
ConcurrentModificationException
- trying to do so will most likely result in
- you don't know the index of the element
- you cannot refer to previous/next element
- efficient in all cases because uses
Iterator
specific for the collection
- efficient in case of
LinkedList
- efficient in case of
- works not only with every
Collection
, but with everyIterable
sinceIterable#iterator()
is used
- you can easily replace
List
with aSet
- no changes to the loop required - you can easily replace with your own class, it just has to implement
Iterable
- you can easily replace
- more robust (less code, fewer special characters)
Summary
for-each
loop wins with a score 3 : 2.
The only reason to use a traditional loop is when:
- the index of element is required, or
- the list has to be modified
add a comment |
up vote
19
down vote
accepted
up vote
19
down vote
accepted
Traditional loop
for (int i = 0; i < list.size(); i++) {
list.get(i).doSomething();
}
- allows to modify the list, e.g.:
- you can add extra element at the end of list and it will be also iterated through
- you know the index
- can be used to refer to another list of the same size
- can be used to refer to previous/next element
- efficient only in
RandomAccess
lists
- in case of
LinkedList
in every iteration of the loop,get(i)
will have to iterate over all elements starting fromhead/tail
toi
- in case of
- works only with
List
sinceList#get(int)
is used - error prone, a lot of things that can go wrong, e.g.:
i = 0;
instead ofint i = 0;
- will refer to variable declared before the loop, possible side effects outside of the loop
>
instead of<
- loop will not execute
j++
instead ofi++
- infinite loop
.get(j)
instead of.get(i)
- will always get the same element
For-each loop
for (Example example : list) {
example.doSomething();
}
- does not allow to modify the list
- trying to do so will most likely result in
ConcurrentModificationException
- trying to do so will most likely result in
- you don't know the index of the element
- you cannot refer to previous/next element
- efficient in all cases because uses
Iterator
specific for the collection
- efficient in case of
LinkedList
- efficient in case of
- works not only with every
Collection
, but with everyIterable
sinceIterable#iterator()
is used
- you can easily replace
List
with aSet
- no changes to the loop required - you can easily replace with your own class, it just has to implement
Iterable
- you can easily replace
- more robust (less code, fewer special characters)
Summary
for-each
loop wins with a score 3 : 2.
The only reason to use a traditional loop is when:
- the index of element is required, or
- the list has to be modified
Traditional loop
for (int i = 0; i < list.size(); i++) {
list.get(i).doSomething();
}
- allows to modify the list, e.g.:
- you can add extra element at the end of list and it will be also iterated through
- you know the index
- can be used to refer to another list of the same size
- can be used to refer to previous/next element
- efficient only in
RandomAccess
lists
- in case of
LinkedList
in every iteration of the loop,get(i)
will have to iterate over all elements starting fromhead/tail
toi
- in case of
- works only with
List
sinceList#get(int)
is used - error prone, a lot of things that can go wrong, e.g.:
i = 0;
instead ofint i = 0;
- will refer to variable declared before the loop, possible side effects outside of the loop
>
instead of<
- loop will not execute
j++
instead ofi++
- infinite loop
.get(j)
instead of.get(i)
- will always get the same element
For-each loop
for (Example example : list) {
example.doSomething();
}
- does not allow to modify the list
- trying to do so will most likely result in
ConcurrentModificationException
- trying to do so will most likely result in
- you don't know the index of the element
- you cannot refer to previous/next element
- efficient in all cases because uses
Iterator
specific for the collection
- efficient in case of
LinkedList
- efficient in case of
- works not only with every
Collection
, but with everyIterable
sinceIterable#iterator()
is used
- you can easily replace
List
with aSet
- no changes to the loop required - you can easily replace with your own class, it just has to implement
Iterable
- you can easily replace
- more robust (less code, fewer special characters)
Summary
for-each
loop wins with a score 3 : 2.
The only reason to use a traditional loop is when:
- the index of element is required, or
- the list has to be modified
edited Nov 7 '15 at 11:58
answered Nov 7 '15 at 11:24
Jaroslaw Pawlak
4,49362149
4,49362149
add a comment |
add a comment |
up vote
3
down vote
They are basically the same, but for-each (the second one) has certain restrictions.
It can be used for accessing the array elements but not for modifying them.
It is not usable for loops that must iterate over
multiple collections in parallel—for example, to compare the elements of two arrays.It can be used only for a single element access and cannot be used to compare successive elements in an array. It is a forward-only iterator. If you want to access only a few elements of the array, you would need to use the traditional for loop.
@Point 1: you can modify the array elements by calling mutable methods. (or you need to specify, what you mean with "modify") I guess what you mean is that one cannot modify the array (orIterable
) itself.
– Tom
Nov 7 '15 at 11:28
add a comment |
up vote
3
down vote
They are basically the same, but for-each (the second one) has certain restrictions.
It can be used for accessing the array elements but not for modifying them.
It is not usable for loops that must iterate over
multiple collections in parallel—for example, to compare the elements of two arrays.It can be used only for a single element access and cannot be used to compare successive elements in an array. It is a forward-only iterator. If you want to access only a few elements of the array, you would need to use the traditional for loop.
@Point 1: you can modify the array elements by calling mutable methods. (or you need to specify, what you mean with "modify") I guess what you mean is that one cannot modify the array (orIterable
) itself.
– Tom
Nov 7 '15 at 11:28
add a comment |
up vote
3
down vote
up vote
3
down vote
They are basically the same, but for-each (the second one) has certain restrictions.
It can be used for accessing the array elements but not for modifying them.
It is not usable for loops that must iterate over
multiple collections in parallel—for example, to compare the elements of two arrays.It can be used only for a single element access and cannot be used to compare successive elements in an array. It is a forward-only iterator. If you want to access only a few elements of the array, you would need to use the traditional for loop.
They are basically the same, but for-each (the second one) has certain restrictions.
It can be used for accessing the array elements but not for modifying them.
It is not usable for loops that must iterate over
multiple collections in parallel—for example, to compare the elements of two arrays.It can be used only for a single element access and cannot be used to compare successive elements in an array. It is a forward-only iterator. If you want to access only a few elements of the array, you would need to use the traditional for loop.
answered Nov 7 '15 at 11:15
Mohammed Aouf Zouag
14.5k22453
14.5k22453
@Point 1: you can modify the array elements by calling mutable methods. (or you need to specify, what you mean with "modify") I guess what you mean is that one cannot modify the array (orIterable
) itself.
– Tom
Nov 7 '15 at 11:28
add a comment |
@Point 1: you can modify the array elements by calling mutable methods. (or you need to specify, what you mean with "modify") I guess what you mean is that one cannot modify the array (orIterable
) itself.
– Tom
Nov 7 '15 at 11:28
@Point 1: you can modify the array elements by calling mutable methods. (or you need to specify, what you mean with "modify") I guess what you mean is that one cannot modify the array (or
Iterable
) itself.– Tom
Nov 7 '15 at 11:28
@Point 1: you can modify the array elements by calling mutable methods. (or you need to specify, what you mean with "modify") I guess what you mean is that one cannot modify the array (or
Iterable
) itself.– Tom
Nov 7 '15 at 11:28
add a comment |
up vote
1
down vote
The second one works with every type of (potentially unordered) Iterable, as it doesn't rely on random access, i.e. get(i)
.
add a comment |
up vote
1
down vote
The second one works with every type of (potentially unordered) Iterable, as it doesn't rely on random access, i.e. get(i)
.
add a comment |
up vote
1
down vote
up vote
1
down vote
The second one works with every type of (potentially unordered) Iterable, as it doesn't rely on random access, i.e. get(i)
.
The second one works with every type of (potentially unordered) Iterable, as it doesn't rely on random access, i.e. get(i)
.
answered Nov 7 '15 at 11:13
Sebastian S
2,06511535
2,06511535
add a comment |
add a comment |
up vote
1
down vote
for(:)
statement is a read-only loop. You cannot change a collection within this loop. Also you cannot use more than one element.
The traditional for
statement doesn't have such limits.
add a comment |
up vote
1
down vote
for(:)
statement is a read-only loop. You cannot change a collection within this loop. Also you cannot use more than one element.
The traditional for
statement doesn't have such limits.
add a comment |
up vote
1
down vote
up vote
1
down vote
for(:)
statement is a read-only loop. You cannot change a collection within this loop. Also you cannot use more than one element.
The traditional for
statement doesn't have such limits.
for(:)
statement is a read-only loop. You cannot change a collection within this loop. Also you cannot use more than one element.
The traditional for
statement doesn't have such limits.
edited Nov 7 '15 at 11:20
answered Nov 7 '15 at 11:15
Andrew Tobilko
23.7k84078
23.7k84078
add a comment |
add a comment |
Difference in what sense?
– Maroun
Nov 7 '15 at 11:13
Premature optimization: Don't. Just... Don't. If you don't have a speed problem, don't solve it. In 99,9% of all cases, you will not notice a difference between the two - except the obvious, with one you have an index (and no iterator) and it only works on methods with a get(x) method, while the other you have no index, an iterator and it works with any collection.
– Florian Schaetz
Nov 7 '15 at 11:14
The second one is more efficient. Because every .get(i) starts a random access search.
– Reinard
Nov 7 '15 at 11:14
@Reinard Potentially yes, depending on the list being iterated through. The
ArrayList
in the example has no speed difference, but aLinkedList
would show noticeable differences.– Kayaman
Nov 7 '15 at 11:17
2
@JaroslawPawlak You should always use a for-each loop, unless you need the index for some reason. (Or in Java 8, you can use streams.) And not because it's faster (it usually isn't) but because it's easier to read.
– biziclop
Nov 7 '15 at 12:06