为什么你不能使用领域的速记初始化数组在Java中的构造函数? [英] Why can't you use shorthand array initialization of fields in Java constructors?

查看:119
本文介绍了为什么你不能使用领域的速记初始化数组在Java中的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看下面的例子:

private int[] list;

public Listing() {
    // Why can't I do this?
    list = {4, 5, 6, 7, 8};

    // I have to do this:
    int[] contents = {4, 5, 6, 7, 8};
    list = contents;
}

为什么我不能用速记初始化?我能想到的解决这个获得的唯一的办法就是让另一个阵列和设置列表该数组。

推荐答案

当你定义的定义行阵,它假定它知道类型是什么,让新INT [] 是多余的。然而,当你使用它的分配不承担它知道数组的类型,所以你必须指定它。

When you define the array on the definition line, it assumes it know what the type will be so the new int[] is redundant. However when you use assignment it doesn't assume it know the type of the array so you have specify it.

当然,其他语言没有这个问题,但在Java中,不同的是在同一行不管你是定义和初始化的字段/变量。

Certainly other languages don't have a problem with this, but in Java the difference is whether you are defining and initialising the fields/variable on the same line.

这篇关于为什么你不能使用领域的速记初始化数组在Java中的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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