Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why list of String has no forEach method?

I have problem with understand why String[] args variable has no forEach method? I can not find any information that this type is not Serializable or Collection because forEach methos implements Serializable.

For example, I have simple main Java class. If I want to use forEach method, I have to first import Arrays class and then on stream use forEach method like below:

import java.util.Arrays;

public class MyClass {
  public static void main(String[] args) {
    Arrays.stream(args).forEach(System.out::println);
  }
}

Why it is not possible to make it just simple like this?

args.forEach(System.out::println);
like image 706
Dawid Avatar asked Jul 30 '19 12:07

Dawid


4 Answers

Short answer: Arrays don't have a forEach method defined on them.

Longer answer: Because it doesn't need it. An array type (using [], not List<>) represents a low level structure in memory, more suited to low level optimisations rather than higher level functional-style code. The hardware of a machine much more closely resembles the imperative, stateful style from languages like C, rather than the functional stateless style from languages like Haskell. Because of this, when creating a lower level data structure like a basic array, it doesn't necessarily make sense to give it more advanced functionality. If you really want a forEach() method, trivially wrap it using Arrays.asList(), Arrays.stream(), or List.of() (depending on Java version).

like image 156
cameron1024 Avatar answered Nov 08 '22 22:11

cameron1024


The main method takes one parameter of type String[]. Which is an Array of Strings.

Lists and Arrays are two different things and only the former does provide a foreach method.

like image 30
jsvilling Avatar answered Nov 08 '22 21:11

jsvilling


Not just String array, Array of any object or primitive types do not have this feature since arrays are the data stricture that is different from other collection implementations

like image 5
kiran Mohan Avatar answered Nov 08 '22 22:11

kiran Mohan


  1. The direct superclass of an array type is Object.
  2. Every array type implements the interfaces Cloneable and java.io.Serializable.

https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html

Any array type doesn't define forEach.

Why?

It simply wasn't implemented and the authors apparently want to keep array types as fundamentally pure as possible.

I don't think this method would be superfluous; on the contrary, I am sure it would be very handy. It's not a trivial task, though. Think about primitive arrays and how you would implement, let's say, a boolean consumer. You would have to bound a plain JDK class BooleanConsumer to a fundamental JVM concept boolean[], or to grand the interface a special status, or to generate the interface on the fly.

like image 4
Andrew Tobilko Avatar answered Nov 08 '22 21:11

Andrew Tobilko