0

foreach loop works for both Iterable interface and array types.

It works by calling the forEach method of Iterable interface.

Do array types in Java have forEach() method, just as Iterable does? Does foreach loop work for array types also by forEach method of array types?

I have read How does primitive array work with new for each loop in Java?, but I am not sure if it answers my question.

  • `array` is a primitive type and primitive types does not have any methods – Johny Nov 21 '17 at 10:27
  • 3
    array types are reference types, not primitive types –  Nov 21 '17 at 10:27
  • you can use Arrays.stream. e.g. Arrays.stream(new int[]{1,2,3,4}).forEach(it -> System.out.println(it)); – devsaki Nov 21 '17 at 10:30
  • @Joe [Arrays](https://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.8) are of reference type, and whether they are arrays of primitive or reference types, they have the following methods, most but not all inherited from `java.lang.Object`: `clone()`, `hashCode()`, `equals()`, `toString()`, `wait()`, `notify()`, `notifyAll()`, ... In addition, they implement the `Serializable` and `Cloneable` interfaces. – user207421 Nov 21 '17 at 10:44

2 Answers2

3

foreach loop works for both Iterable interface and array types.

Correct.

It works by calling the forEach method of Iterable interface.

No it doesn't.

Do array types in Java have forEach() method, just as Iterable does?

No. See here for details of what they have.

Does foreach loop work for array types also by forEach method of array types?

No.

I have read How does primitive array work with new for each loop in Java?, but I am not sure if it answers my question.

It does.

user207421
  • 305,947
  • 44
  • 307
  • 483
2

The forEach method introduced in Java 8 in the Iterable interface has nothing to do with what you call "foreach loop" (the actual name is enhanced for loop).

The enhanced for loop was introduced in an earlier Java version, and doesn't use the forEach() method. It uses the iterator() method implemented by classes that implement Iterable. For arrays it works without an iterator. It just uses the indices of the array to loop over the elements.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thanks. When is `forEach` method of `Iterable` used, if it is not used in foreach loop? –  Nov 21 '17 at 10:37
  • @Ben when you write code that uses it + some JDK code that uses it - for example, `Collections.CheckedCollection` calls it (I just ran a search and found out). – Eran Nov 21 '17 at 10:39
  • Is it correct that code that calls `forEach` method of `Iterable` is always replaceable by code using foreach loop? –  Nov 21 '17 at 10:39
  • @Ben I believe it is. You can always dump the body of the Consumer passed to the `forEach()` method into the body of a foreach loop. – Eran Nov 21 '17 at 10:43