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);
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).
The main method takes one parameter of type String[]
. Which is an Array
of String
s.
List
s and Array
s are two different things and only the former does provide a foreach method.
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
- The direct superclass of an array type is
Object
.- Every array type implements the interfaces
Cloneable
andjava.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With