Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display 1 to 100 without loop or recursion

Tags:

java

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.]

like image 247
Priyatam Roy Avatar asked Dec 25 '22 05:12

Priyatam Roy


2 Answers

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.

like image 101
user1717259 Avatar answered Jan 13 '23 04:01

user1717259


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

like image 36
Force0234 Avatar answered Jan 13 '23 04:01

Force0234