如何在 Java 中创建对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16396545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:41:22  来源:igfitidea点击:

How to create an Array of Objects in Java

javaarraysobject

提问by KDM

I'm trying to create an array of objects as defined by a subclass (I think that's the correct terminology). I can see that the question is recurring, but implementation is still problematic.

我正在尝试创建一个由子类定义的对象数组(我认为这是正确的术语)。我可以看到这个问题反复出现,但实施仍然存在问题。

My code

我的代码

public class Test {

    private class MyClass {
        int bar = -1;
    }

    private static MyClass[] foo;

    public static void main(String args[]) {

        foo = new MyClass[1];
        foo[0].bar = 0;

    }       
}

Gives the error

给出错误

Exception in thread "main" java.lang.NullPointerException.

线程“main”中的异常 java.lang.NullPointerException。

In an attempt to rationalise it, I broke it down to simplest terms:

为了使其合理化,我将其分解为最简单的术语:

public class Test {

    private static int[] foo;

    public static void main(String args[]) {

        foo = new int[1];
        foo[0] = 0;

    }       
}

Which appears to work. I just don't see the difference between my two examples. (I understand that my first is pointless, but MyClass will ultimately contain more data.)

这似乎有效。我只是没有看到我的两个例子之间的区别。(我知道我的第一个毫无意义,但 MyClass 最终将包含更多数据。)

I'm pretty sure the question is asked hereand is very well answered. I think I implemented the solution:

我很确定这个问题在这里被问到并且得到了很好的回答。我想我实施了解决方案:

MyClass[] foo = new MyClass[10];
foo[0] = new MyClass();
foo[0].bar = 0;

but the second line of the above issues the error

但上面的第二行发出错误

No enclosing instance of type Test is accessible.

没有可访问类型 Test 的封闭实例。

I do understand that ArrayList would be a way forward, but I'm trying to grasp the underlying concepts.

我确实理解 ArrayList 将是一种前进的方式,但我试图掌握基本概念。

NB - It might be useful to know that while very comfortable with programming in general, Java is my first dip into Object Oriented programming.

NB - 知道虽然通常对编程非常熟悉,但 Java 是我第一次涉足面向对象编程,这可能很有用。

采纳答案by Bernhard Barker

The reason intworks, but MyClassdoesn't:

原因int有效,但MyClass无效:

From here:

这里

Data Type               Default Value (for fields)
byte                    0
short                   0
int                     0
long                    0L
float                   0.0f
double                  0.0d
char                    '\u0000'
String (or any object)  null
boolean                 false

When you initialize an array, all elements take on the default value.

初始化数组时,所有元素都采用默认值。

So, when you initialize an int[], all elements are 0, so no problem using that or assigning a new value to it.

因此,当您初始化 an 时int[],所有元素都为 0,因此使用它或为其分配新值都没有问题。

But, when you initialize an MyClass[], all elements are null, which is a problem when you try to access a member of one of the elements.

但是,当您初始化 时MyClass[],所有元素都是null,当您尝试访问其中一个元素的成员时,这是一个问题。

If you don't know why accessing a nullobject's members won't work, you probably need to take 2 steps back and read a Java book.

如果您不知道为什么访问null对象的成员不起作用,您可能需要退后两步并阅读一本 Java 书籍。

Additional Note:

附加说明:

Technically, this:

从技术上讲,这:

int[] foo = new int[1];
foo[0] = 0;

is actually more like this:

实际上更像是这样:

MyClass[] foo = new MyClass[10];
foo[0] = new MyClass();

not:

不是:

MyClass[] foo = new MyClass[10];
foo[0].bar = 0;

since you're assigning a new value to an element, rather than accessing a member of an element.

因为您正在为元素分配一个新值,而不是访问元素的成员。

No enclosing instance of type Test is accessible:

没有可访问类型 Test 的封闭实例:

The other answers cover that pretty well, and here are 3 related questions:

其他答案很好地涵盖了这一点,这里有 3 个相关问题:

No enclosing instance of type is accessible.

没有封闭的类型实例是可访问的。

No enclosing instance of type Server is accessible

无法访问类型服务器的封闭实例

"No enclosing instance of type" error while calling method from another class in Android

从 Android 中的另一个类调用方法时出现“无封闭类型实例”错误

回答by Joachim Sauer

The problem you faced at the end ("no enclosing instance") is not actually related to arrays at all.

您最后面临的问题(“无封闭实例”)实际上与数组根本无关。

Try replacing your last code block with this:

尝试用这个替换你的最后一个代码块:

 MyClass foo = new MyClass();

You'll get the exact same error message, even though no arrays are involved.

即使不涉及数组,您也会收到完全相同的错误消息。

The problem here is that a non-static inner class has an implicit reference to its outer instance. Since you have no outer instance (you're in a static context, there is no this), no MyClassinstance can be created.

这里的问题是非静态内部类具有对其外部实例的隐式引用。由于您没有外部实例(您处于静态上下文中,因此没有this),MyClass因此无法创建任何实例。

You probablydidn't need/want a inner class and can simply make it static:

可能不需要/想要一个内部类,可以简单地做到static

private static class MyClass

Also: the reason your code worked with intand not with MyClassis that an int[]holds intvalues(intis a primitive type), while a MyClass[]holds MyClassreferences(MyClassis a reference type).

另外:您的代码使用int而不是使用的原因MyClass是一个int[]持有intint是一种原始类型),而一个MyClass[]持有MyClass引用MyClass是一种引用类型)。

回答by Rahul Bobhate

The classMyClassis an inner class, and not a subclass. Non-static inner classes can be accessed by creating an object of class enclosing the inner class. So, if you want to access the inner class, you would have to create an object of outer class first. You can do it by:

classMyClassinner class,而不是一个子类别。可以通过创建包含内部类的类对象来访问非静态内部类。因此,如果要访问内部类,则必须先创建外部类的对象。你可以这样做:

Test t = new Test();
MyClass[] foo = new MyClass[10];
foo[0] = t.new MyClass();
foo.bar = 0;

回答by Tony the Pony

You cannot use a non-static inner class from within the static mainmethod.

您不能在静态main方法中使用非静态内部类。

The solution is to declare MyClassas private static class.

解决方案是声明MyClassprivate static class.