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

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

问题描述

我可以这样写:

  ACLASS []数组= {object1,Object2的}

我也可以这样写:

  ACLASS []数组=新ACLASS [2];
...
数组[0] = object1;
阵列[1] = Object2的;

但我不能写:

  ACLASS []数组;
...
阵列= {object1,Object2的};

这是为什么阻止Java的?

我知道如何解决它,但不时会比较简单。

例如:

 公共无效selectedPointsToMove(cpVect坐标){    如果(标签== NULL){
        如果(arePointsClose(坐标,点1,10)){
            cpVect [] = tempTab {}点1;
            标签= tempTab;
        }否则如果(arePointsClose(点2,坐标,10)){
            cpVect [] = tempTab {}点2;
            标签= tempTab;
        }其他{
            cpVect [] = tempTab {点1,点2};
            标签= tempTab;
        }
    }
}

<子>的这个简单的问题,因为我学会了如何使用数组在Java中发挥已经缠着我。


解决方案

  

这是为什么阻止Java的?


您得问Java的设计者。有可能是限制一些微妙的语法原因。注意:在Java 1.1中添加的一些数组创建/初始化构造都不在Java 1.0中,和(IIRC)。

但为什么是不重要......的限制是存在的,你必须忍受它。


  

我知道如何解决它,但不时会比较简单。


您可以这样写:

  ACLASS []数组;
...
阵列=新ACLASS [] {object1,Object2的};

I can write:

AClass[] array = {object1, object2}

I can also write:

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

but I can't write:

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

Why is this blocked by Java?

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

For example:

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

This simple question that has been bugging me since I learned how to play with arrays in Java.

解决方案

Why is this blocked by Java?

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.

You can write this:

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

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

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