veera sangham wrote:what is difference between foreach and for?
Which gives better perfomance?
please give reply ........
Campbell Ritchie wrote:Note that the for-each loop operates on a copy of the element. So something like... will print Campbell several times, whilst leaving the original array or collection unchanged.
Mike Simmons wrote:Well, the reference is copied
If you've got mutable objects in the collection, you can certainly alter them inside a for loop.
Campbell Ritchie wrote:The Iterable<E> interface was introduced in Java5 along with the for-each loop; the two support each other. Any collections class which supported the iterator() method was retrofitted to implement the Iterable<E> interface. The way this was done was to change the Collection<E> interface to Collection<E> extends Iterable<E>. Since interfaces like Set<T> and List<T> already extend Collection<T>, this means any List<E> or Set<E>, etc. is also an Iterable<E>. The iterator() method was put into the Iterable<E> interface (I can’t remember whether it is removed from Collection<E> or not).
Maps<K, V> have never implemented an iterator() method, because you never go through a Map<K, V>. You go through its Ks or its Vs, so you can get them as a Set<K> or a Set<V>, which you can traverse with a for-each loop, since th/ose are now Iterable<E> objects.
Campbell Ritchie wrote:
Maps<K, V> have never implemented an iterator() method, because you never go through a Map<K, V>. You go through its Ks or its Vs, so you can get them as a Set<K> or a Set<V>...
Campbell Ritchie wrote:You go through its Ks or its Vs, so you can get them as a Set<K> or a Set<V>, which you can traverse with a for-each loop, since th/ose are now Iterable<E> objects.
SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
Maybe he went home and went to bed. And took this tiny ad with him:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
|