0

I would like to know how constructors with variable arguments work. Here is an example :

import java.util.ArrayList;
import java.util.List;

public class VehicleCompany {
private List<Vehicle> vehicles= new ArrayList<Vehicle>();

private void VehicleCompany (Vehicle... vehicles) {
 //how to complete it?
}

Which way is the easier to do it? I found that I can copy the argumenttaxis into another list or use a for-loop but didn't how to do since this.taxis.size() is 0.

Any suggestions? Thanks!

7
  • Hint: vehicles will be an array of Vehicle objects (just like Vehicle[] vehicles) Commented Sep 15, 2016 at 19:34
  • I think you'll find your answer in this post : stackoverflow.com/questions/2330942/… Commented Sep 15, 2016 at 19:36
  • ArrayList work the best for me so I can't use an array Commented Sep 15, 2016 at 19:37
  • 1
    Arrays.asList() may help. Commented Sep 15, 2016 at 19:41
  • 1
    1) Constructors with variable arguments work the same way as all other methods in Java with variable arguments. 2) What taxis? 3) What does "this.taxis.size() is 0" have to do with copying from parameter to field? The field will grown as needed. It's what an ArrayList does. Commented Sep 15, 2016 at 20:12

1 Answer 1

2

A vararg is effectively converted into an array. So you can convert it to a list with Arrays.asList() as you would with any other array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.