开发者

Initializing Java object instances containing an array of objects

开发者 https://www.devze.com 2022-12-21 16:52 出处:网络
The following code is correct: public Sample mOboe开发者_如何学CSamples[] = { new Sample(1,1), new Sample(1,2) };

The following code is correct:

public Sample mOboe开发者_如何学CSamples[] = { 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'?


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 new expression, the braces aren't valid syntactically (because they're initializers -- in this case -- but you haven't said there's anything there to initialize).


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));
0

精彩评论

暂无评论...
验证码 换一张
取 消