不在声明中时的数组初始化语法 [英] Array initialization syntax when not in a declaration

查看:25
本文介绍了不在声明中时的数组初始化语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以写:

AClass[] array = {object1, object2}

我也可以写:

AClass[] array = new AClass[2];
...
array[0] = object1;
array[1] = object2;

但我不会写:

AClass[] array;
...
array = {object1, object2};

为什么这会被 Java 阻止?

Why is this blocked by Java?

我知道如何解决它,但有时它会更简单.

I know how to work around it, but from time to time it would be simpler.

例如:

public void selectedPointsToMove(cpVect coord) {

    if (tab == null) {
        if (arePointsClose(coord, point1, 10)) {
            cpVect[] tempTab = {point1};
            tab = tempTab;
        } else if (arePointsClose(point2, coord, 10)) {
            cpVect[] tempTab = {point2};
            tab = tempTab;
        } else {
            cpVect[] tempTab = {point1,point2};
            tab = tempTab;
        }
    }
}

这个简单的问题一直困扰着我,因为我学会了如何在 Java 中使用数组.

推荐答案

为什么这会被 Java 阻止?

Why is this blocked by Java?

您必须询问 Java 设计人员.限制可能有一些微妙的语法原因.请注意,一些数组创建/初始化构造不在 Java 1.0 中,并且 (IIRC) 在 Java 1.1 中添加.

You'd have to ask the Java designers. There might be some subtle grammatical reason for the restriction. Note that some of the array creation / initialization constructs were not in Java 1.0, and (IIRC) were added in Java 1.1.

但为什么"并不重要……限制就在那里,你必须接受它.

But "why" is immaterial ... the restriction is there, and you have to live with it.

我知道如何解决它,但有时它会更简单.

I know how to work around it, but from time to time it would be simpler.

你可以这样写:

AClass[] array;
...
array = new AClass[]{object1, object2};

这篇关于不在声明中时的数组初始化语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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