How can I put a Java array inside itself?

You're running into a casting error since you've declared theArray to be an Array of Objects. As a result, you can't promise Java that theArray[1] is an Array--it could be any kind of Object. You'll need to break up your access to do what you want:

Object[] innerArray = (Object[]) theArray[1];
System.out.println(innerArray[0] == theArray[0]); // Always true since innerArray IS theArray
while (true) {
    // Careful! This loops forever!
    // set innerArray = innerArray[1] = theArray = theArray[1] = innerArray... 
    // all of these are the exact same object (but you have to tell Java their type every time)
    innerArray = (Object[]) innerArray[1]; 
    System.out.println(innerArray[0]);
}

Your code is equivalent to

Object arr = theArray[1];  // arr is an Object here, not an array 

But you could do

Object[] arr = (Object[] ) theArray[1];    // Now it is an array

theArray[1] is of compile-time type Object (since it comes from an array of Objects).

You need to cast it to Object[] to use it as an array.


The fundamental problem you're encountering is that although an array that contains itself is a perfectly valid object, it isn't a valid type.

You can nest array types arbitrarily deeply – Object[][][][][][][][][][][][][] is a valid type.
However, the "bottom level" of the type can't be an array.

You're trying to create a type which is an array of itself.
Using generics, that would be possible:

class Evil extends ArrayList<Evil> { }

Tags:

Java

Arrays