初始化包含对象数组的 Java 对象实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2373748/
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-10-29 20:50:18  来源:igfitidea点击:

Initializing Java object instances containing an array of objects

javaarraysobjectinitialization

提问by Mark

The following code is correct:

以下代码是正确的:

public Sample mOboeSamples[] = { new Sample(1,1), new Sample(1,2) };
public Sample mGuitarSamples[] = { new Sample(1,1), new Sample(1,2) };
public SampleSet mSampleSet[] = { 
        new SampleSet( "oboe",  mOboeSamples ),
        new SampleSet( "guitar", mGuitarSamples)
        };

but I'd like to write something like:

但我想写一些类似的东西:

public SampleSet mSampleSet[] = { 
        new SampleSet( "oboe",  { new Sample(1,1), new Sample(1,2) } ),
        new SampleSet( "guitar", { new Sample(1,1), new Sample(1,2) } )
        };

This does not compile.

这不编译。

Is there some bit of syntax I'm missing, or is this a language 'feature'?

是否有一些我遗漏的语法,或者这是一种语言“功能”?

回答by T.J. Crowder

You need to tell it the type of the arrays you're passing as parameters:

您需要告诉它您作为参数传递的数组的类型:

public SampleSet mSampleSet[] = { 
    new SampleSet( "oboe",   new Sample[] { new Sample(1,1), new Sample(1,2) } ),
    new SampleSet( "guitar", new Sample[] { new Sample(1,1), new Sample(1,2) } )
};

Without the newexpression, the braces aren't valid syntactically (because they're initializers -- in this case -- but you haven't said there's anything there to initialize).

如果没有new表达式,大括号在语法上无效(因为它们是初始化器——在这种情况下——但你没有说有什么要初始化的)。

回答by polygenelubricants

Use varargs:

使用可变参数

 SampleSet(String name, Sample... samples) {
    // exactly the same code as before should work
 }

Then you can do

然后你可以做

 new SampleSet("oboe", new Sample(1, 1), new Sample(1, 2));