Wednesday, July 26, 2023

How to Create and Initialize Anonymous Array in Java? Example

Anonymous arrays in Java is an Array without any name, just like Anonymous inner classes and policy of using Anonymous array is just create, initialize and use it, Since it doesn't have any name you can not reuse it. The anonymous array was a good way to implement variable argument methods before Java introduced varargs in Java5. You had the liberty to create an array of any length and pass that to a method that operates on an anonymous array. Classical example of such variable argument method is aggregate function like sum(), avg(), min(), max() etc.

In this java anonymous array tutorial, we will how to create an anonymous array, how to initialize them, and an example of an anonymous array as a variable argument method.

Before going for a programming/coding interview, It's absolutely necessary to do as much practice in data structure and algorithm as possible to take advantage of all the knowledge available. 

How to Create and Initialize Anonymous Array in Java? Example




Anonymous array in Java Example Tutorial

How to create an Anonymous array in Java

Anonymous array example java create initializeAnonymous array follows same syntax like normal array in Java e.g. new [] { }; , only difference is that after creating Anonymous array we don't store it on any reference variable. here is
few examples of creating anonymous array in java:

anonymous int array : new int[] { 1, 2, 3, 4};
anonymous String array : new String[] {"one", "two", "three"};
anonymous char array :  new char[] {'a', 'b', 'c');

as you have noticed just like anonymous class, the creation and initialization of an anonymous array is done at the same time. you initialize them in the same line where you create using new(). as they don't have names there is no way you can initialize() them later.



Anonymous Array Example in Java

Best use of anonymous array is to implement variable argument method which can be invoked with a different number on arguments. these methods accept an array type and when code invokes this method it creates an anonymous array of different length and pass to a method for processing. here is a complete code example of anonymous array method:

public class AnnonymousArrayExample {

    public static void main(String[] args) {
       
        //calling method with anonymous array argument
        System.out.println("first total of numbers: " + sum(new int[]{ 1, 2,3,4}));
        System.out.println("second total of numbers: " + sum(new int[]{ 1, 2,3,4,5,6,}));
      
    }
    
    //method which takes an array as argument
    public static int sum(int[] numbers){
        int total = 0;
        for(int i: numbers){
            total = total + i;
        }
        return total;
    }
}

same method sum() can also be implemented using varargs in Java like public static int sum(int... numbers) but you cannot have sum(int[] numbers) and sum(int... numbers) method in one class Java will throw compilation error because it internally used an anonymous array to pass variable argument list.


Related Java Tutorial

5 comments:

  1. Hi Javin ,

    Gr8 Article , one more thing that I want to add is..There's no such thing as an "anonymous inner array" - what you've got there is simply an array creation expression.

    To use varargs arrays, you just change the method declaration like this:

    public class AnnonymousArrayExample {

    public static void main(String[] args) {

    // calling method with anonymous array argument
    System.out.println("first total of numbers: "
    + sum(new int[] { 1, 2, 3, 4 }));
    System.out.println("second total of numbers: "
    + sum(new int[] { 1, 2, 3, 4, 5, 6, }));

    }

    // method which takes an array as argument
    public static int sum(int... numbers) {
    int total = 0;
    for (int i : numbers) {
    total = total + i;
    }
    return total;
    }
    }

    ReplyDelete
  2. There is no such thing as an "anonymous" and "non-anonymous" array. I think you are trying to draw a parallel here to anonymous classes. And I think it's a really bad one.

    It's important to realize the difference between classes, instances and fields. A class is like a blueprint that can be instantiated mutliple times, resulting in multiple instances. And a single instance can be assigned to one or more fields or none at all. An instance doesn't really need to be assigned to something to do its thing. And assigning it to 2 fields will not make a copy, it will still point to the same instance. To understand my comment you must understand this first. Because it's really fundamental.

    When we talk about something being "anonymous", then we are talking about names, right ?
    A class only has 1 name, which is immutable. Since a class is just a blueprint, it has a name even if no instances are available. The term "anonymous" does not refer to the name of the instances, it refers to the fact that the class (i.e. the blueprint) has no name. And that's really important.

    Your "anonymous array" definition, talks about the fact that its not assigned to an instance, and that therefore there is no instance-name. But, you can really do this for EVERY instance in java. You can do this for an Integer, String, Double, .... whatever you like. It's no big deal, there's nothing special about it.

    But certainly, there is no parallel with anonymous classes.

    I am just guessing here, but maybe you got inspired by programming structures that exist in javascript. I've seen how arrays are sometimes used to mimick classes in javascript. But really, I wouldn't try to compare java and javascript when it comes to design patterns, because the 2 are totally different.

    ReplyDelete
  3. @BramVdb, Anonymous class is quite different than anonymous array. Here it refers to adhoc arrays which are created on demand.

    ReplyDelete
  4. Totally agree with BramVdb. Anonymous array is a stretch, computer pseudoscience. Following the same logic one can write: a method like that:
    some_name( new String("xx"), new Object(), new Double(7.3)); ... and afterwords name these variables in a function definition just like you did with an array. We can have anonymous everything that inherits from Object. So your trick is actually more generic than array and I'd rather perceive it as deferred naming. than anonymous.

    ReplyDelete