← All articles

Curly Braces Column: Fun with Java Arrays

Elegant array development might encompass reflection, generics, and lambdas.

Eric J. Bruno

I was recently working with a colleague who is primarily a C developer. The conversation came to arrays and how different they work in Java compared to C, which was surprising to him given how Java is considered a C-like language. Let’s explore arrays in Java and its idiosyncrasies. It starts simple, but quickly gets interesting.

Declaring an Array

If you follow a tutorial on Java, you’ll see there are two ways to declare an array. The first is straightforward:

int[] array; // a Java array declaration

Right away you can see how it differs from C, where the proper syntax is:

int array[]; // a C array declaration

That’s enough of the language comparison. Let’s focus on Java. The next step is to allocate the array:

array = new int[10]; // Java array allocation

First, you cannot take a shortcut and do this instead:

int[10] array; // NOPE, ERROR!

So just forget that one now. However, you can declare and initialize an array in one step:

int[] array = { 0, 1, 1, 2, 3, 5, 8 };

That’s fine if you know the values up front. Here’s the code you’ll encounter more often to declare, allocate, and use an int array:

int[] array;  
array = new int[10];  
array[0] = 0;  
array[1] = 1;  
array[2] = 1;  
array[3] = 2;  
array[4] = 3;  
array[5] = 5;  
array[6] = 8;  
...

Notice I said “int” array, which is an array of Java primitive types. Let’s try the same thing with an array of Java objects:

class SomeClass {  
    int val;  
    // …  
}  
SomeClass[] array = new SomeClass[10];  
array[0].val = 0;  
array[1].val = 1;  
array[2].val = 1;  
array[3].val = 2;  
array[4].val = 3;  
array[5].val = 5;  
array[6].val = 8;

If you run this, you’ll get an exception as soon as you try to use the first array element. This is because, although the array is allocated, the array buckets each contain null object references. If you type this into your IDE, it will even autocomplete the “.val” for you, so this can be confusing. Instead, you need to do the following (new code in bold):

SomeClass[] array = new SomeClass[10];  
for ( int i = 0; i < array.length; i++ ) {  
    array[i] = new SomeClass();  
}  
array[0].val = 0;  
array[1].val = 1;  
array[2].val = 1;  
array[3].val = 2;  
array[4].val = 3;  
array[5].val = 5;  
array[6].val = 8;

It has often frustrated me that I cannot more easily allocate the array, and the objects within the array, with less code, maybe even all in one line. So I began experimenting.

Towards Java Array Nirvana

The goal here is elegance, not to be a purist. Smells like “clean code” spirit! And in that spirit, let’s set out to create some reusable code to help clean up the array allocation pattern. Here’s a first attempt:

public class MyArray {  
      
    public static Object[] toArray(Class cls, int size)   
      throws Exception {  
        Constructor ctor = cls.getConstructors()[0];  
        Object[] objects = new Object[size];  
        for ( int i = 0; i < size; i++ ) {  
            objects[i] = ctor.newInstance();  
        }  
          
        return objects;  
    }

    public static void main(String[] args) throws Exception {  
        SomeClass[] array1 = (SomeClass[])MyArray.toArray(SomeClass.class, 32);  
        System.out.println(array1);  
    }  
}

The one line of code in bold is essentially what we’re after, thanks to the implementation of toArray. This method uses Java Reflection to find the default constructor for the provided class, then calls it to instantiate an object of this class. It does this once for each element of the array. Brilliant! Too bad it doesn’t work. It compiles fine, but results in a ClassCastException when you run it. In order to use this code, we need to handle it as an array of Objects, and then cast each array element to class SomeClass:

Object[] objects = MyArray.toArray(SomeClass.class, 32);  
SomeClass scObj = (SomeClass)objects[0];  
...

Bleh! To resolve this, I turn once again to Java Reflection.

Solution 1: Use Java Reflection

The answer to the issues above is to use the java.lang.reflect.Array class to instantiate an array of the class we specify, instead of the base java.lang.Object. This is essentially a one-line code change that gets us closer to our goal:

public static Object[] toArray(Class cls, int size) throws Exception {  
    Constructor ctor = cls.getConstructors()[0];  
    Object array = Array.newInstance(cls, size);  
    for ( int i = 0; i < size; i++ ) {  
        Array.set(array, i, ctor.newInstance());  
    }  
    return (Object[])array;  
}

Now we can use this to get an array of the class we desire, and then operate on it as such:

SomeClass[] array1 = (SomeClass[])MyArray.toArray(SomeClass.class, 32);

Although not a necessary change, the second line in bold was modified to use Java Reflection’s Array class to set each array element’s content. This is great! But there’s one more detail that does not feel quite right: that cast to SomeClass[]. Fortunately, there is a solution.

Solution 2: Use Java Generics

If you’ve used the Java Collection classes, you know that they use Java Generics to be type-specific, and eliminate casts in many of their operations. We can use Generics here as well. Take java.util.List, for example:

List list = new ArrayList();  
list.add( new SomeClass() );  
SomeClass sc = list.get(0); // Error, needs a cast unless...

The line in bold will result in an error, unless you update the first line:

List<SomeClass> = new ArrayList();

We can achieve the same result using Generics in the MyArray class. Here are the changes:

public class MyArray<E> {  
    public <E> E[] toArray(Class cls, int size) throws Exception {  
        E[] array = (E[])Array.newInstance(cls, size);  
        Constructor ctor = cls.getConstructors()[0];  
        for ( int element = 0; element < array.length; element++ ) {  
            Array.set(array, element, ctor.newInstance());  
        }  
        return arrayOfGenericType;  
    }  
}  
// ...  
MyArray<SomeClass> a1 = new MyArray(SomeClass.class, 32);  
SomeClass[] array1 = a1.toArray();

Ahhh, now this looks good! By using Generics, and including the target type in the declaration, the type can be inferred in other operations. In fact, this can be reduced to a single line, if we choose:

SomeClass[] array = new MyArray<SomeClass>(SomeClass.class, 32).toArray();  

So, mission accomplished, right? Well, not quite. This is fine if you don’t care which class constructor you’re calling. If you want to call a specific constructor, this solution falls short. You can continue to use Reflection to attempt to solve this, but the code may get complex. Fortunately, Java offers another solution: Lambdas.

Solution 3: Use Java Lambdas

I’ll admit, I was slow to adopt Lambdas, but I’ve grown to appreciate their value. In fact, Java Magazine has published many good use cases to explore, like this one, and this one, which have influenced me. In particular, I’ve come to like the java.util.stream.Stream class, which is meant to process collections of objects. It’s the Stream class that helps achieve Java array nirvana, in my opinion. Here’s a first attempt:

SomeClass[] array =   
    Stream.generate(() \-> new SomeClass())  
        .toArray(SomeClass[]::new);

I broke this up across three lines for readability. You can see it checks all the boxes: it is simple and elegant, creates a populated array of instantiated objects, and allows us to call a specific constructor. Notice the parameter to the toArray method: SomeClass[]::new. This is a generator function used to allocate an array of the specified type.

However, as it stands this code has a minor issue: it creates an array of infinite size. Fortunately, we can resolve that by calling the limit method:

SomeClass[] array = Stream.generate(() \-> new SomeClass())  
    .limit(32)  
    .toArray(SomeClass[]::new);

Now the array is limited to 32 elements. You can even set specific object values for each array element, as in:

SomeClass[] array = Stream.generate(() \-> {  
        SomeClass result = new SomeClass();  
        result.val = 16;  
        return result;  
    })  
    .limit(32)  
    .toArray(SomeClass[]::new);

That’s the power of Lambdas, but I’m not sure how I feel about the code above, as it is not compact. Calling a different constructor to set the value is much cleaner, in my opinion:

SomeClass[] array6 = Stream.generate( () \-> new SomeClass(16) )  
    .limit(32)  
    .toArray(SomeClass[]::new);

I like the Lambda-based solution, especially when you need to call a specific constructor or operate on each array element. When I need something more basic, I tend to use the solution based on Generics since it’s simpler. However, you can see that Lambdas provides an elegant and flexible solution.

Conclusion

In this journey we’ve explored a lot about Java: declaring and allocating arrays of primitives, allocating arrays of Objects, using Java Reflection, and a powerful use case for Java Lambdas. And we did this all for a noble cause: to write elegant and compact Java code. Mission complete! Hopefully you’re encouraged to dive deeper using the links throughout this article. Afterward, you should try this quiz recently published in Java Magazine online to see how you do, just for fun.

Keep reading

More articles

  1. On this site12 min read

    HTML5 Server-Sent Events with Micronaut, Revisited

    EventPost, formerly MessageServer, is a simple, reliable messaging server built on Micronaut's support for HTML5 server-sent events, with queues and publish/subscribe topics over plain HTTP. The new version runs on Micronaut 5 and Java 26, stores queued messages off the Java heap in NoHeapDB, and fixes bugs that only showed up under load.

  2. On this site34 min read

    Building a Zero-GC Database in Java: Adventures in Off-Heap Storage

    NoHeapDB keeps data in process, in the same JVM, but stores it completely outside the Java heap and without relying on JNI. The first version did this with ByteBuffer.allocateDirect(). It uses MemorySegment and Arena from Java's Foreign Function and Memory (FFM) API. A store can live in memory or survive a restart as memory-mapped files. Either way, the GC never sees the stored data.

  3. blogs.oracle.com

    Curly Braces Column: Writing SOLID Java Code

    Following the Robert C. Martin's five principles of SOLID object-oriented design (OOD)can make you a better Java developer.