我怎样才能把一个Java数组里面本身? [英] How can I put a Java array inside itself?

查看:131
本文介绍了我怎样才能把一个Java数组里面本身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个Java对象阵列和阵列置于内本身在其第二个索引(以重present自相似的分形与阵列),但是当我尝试访问 theArray [1] [1] [0] ,我得到这个错误:

I'm attempting to create a Java object array and place the array inside itself at its second index (in order to represent a self-similar fractal with the array), but when I try to access theArray[1][1][0], I get this error:

Main.java:11:错误:所需的数组,但对象中找到

这是我到目前为止已经试过了,我不知道为什么它不工作:

This is what I've tried so far, and I'm not sure why it's not working:

import java.util.*;
import java.lang.*;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Object[] theArray = new Object[2];
        theArray[0] = "This array should contain itself at its second index.";
        theArray[1] = theArray; //Now I'm attempting to put the array into itself.
        System.out.println(theArray[1][1][0]) //Main.java:11: error: array required, but Object found
    }
}

时,它实际上可能把Java数组里面本身,我试图在这里做什么?

Is it actually possible to put a Java array inside itself, as I'm attempting to do here?

推荐答案

theArray [1] 编译时间的类型<$ C的$ C>对象(因为它来源于对象的数组)。

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.

您可以嵌套数组类型任意深深&ndash的; 对象[] [] [] [] [] [] [] [] [] [] [] [] [] 是一个有效的类型。结果
然而,该类型的底层不能是一个数组。

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> { }

这篇关于我怎样才能把一个Java数组里面本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆