I found the solution to this problem but can't figure out how it works. Can someone please explain this?
public static void main(String[] args) {
Object[] numbers = new Object[100];
Arrays.fill(numbers, new Object() {
private int count = 0;
@Override
public String toString() {
return Integer.toString(++count);
}
});
System.out.println(Arrays.toString(numbers));
}
[I could not comment to that answer directly because I dont have enough reputation points.]
Can someone please explain this?
This code is a use of
Arrays.fill(Object[] a, Object val)
Where the Object val
provided is an anonymous class with its toString() method overridden.
Arrays.toString(numbers) calls the toString() on the anonymous class for each element in the a
array. As the toString() is overridden to increment the count, you get incremented values each time it is called.
However, as @Eran has pointed out, it is not without a loop.
To be accurate, Arrays.fill()
use a loop in its own implementation.
In general, Arrays.fill
fills an array by assigning the second parameter to every element of the first parameter (your array).
Your example has an Array
of type Object
and a length of 100 elements.
In Arrays.fill(...)
you generate a so-called anonymous class of type Object, which reimplements the toString
-method by increasing the value of a counter (int count
) and printing it after that.
Now, by calling Arrays.toString
the toString()
method of every element inside the array is executed (which is the same instance of the anonymous class here), resulting in printing the numbers from 1-100
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