为什么不是Java数组初始化的对象? [英] Why doesn't Java initialize Array Objects?

查看:143
本文介绍了为什么不是Java数组初始化的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果持斧以下code在java中:

If one runs the following code in java:

public class Testing {

    public static void main(String[] args) {
        TestObject[] array = new TestObject[4];
        //array[0] = new TestObject();
        System.out.println(Arrays.asList(array));
    }
}

class TestObject {
    String aString;

    public TestObject() {
        aString = "This has been initialized.";
    }
}

这将打印(NULL,NULL,NULL,NULL),如果数组[0] =新的TestObject(); 是取消注释,那么第一个对象将有内存地址(而不是为null)。我只是困惑,为什么Java的会不会自动在一个阵列时,第一次正确初始化数组调用构造函数的每个对象。什么是它现在的工作方式的优势是什么?它是一个空间的问题(如这将是成本太高这样做)?

It will print (null, null, null, null), and if array[0] = new TestObject(); is uncommented, then the first object will have a memory address (and not be null). I'm just confused to as to why Java wouldn't automatically call the constructor for each Object in an array when the array is first initialized properly. What are the advantages of the way it works right now? Is it a space issue (as in it would be too costly to do so)?

也许我只是忽略了一些愚蠢的或者我只是错了。这是没有直接关系,我有一个问题,所以如果它是错误的论坛上,我表示歉意。

Maybe I've just overlooked something silly or I'm simply mistaken. This is not directly related to a problem I'm having, so if it's the wrong forum I apologize.

推荐答案

如果你想填补你的阵列是的TestObject的子类,或与非默认构造函数构造的真实物体会发生什么?在现实世界中,你很少想了一堆相同对象的数组。

What happens if you want to fill up your array with real objects that are subclasses of TestObject, or which are constructed with non-default constructors? In the real world, you rarely want an array with a bunch of identical objects.

这篇关于为什么不是Java数组初始化的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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