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!

Takichiii
  • 453
  • 4
  • 14
  • 27
  • Hint: `vehicles` will be an array of `Vehicle` objects (just like `Vehicle[] vehicles`) – BackSlash Sep 15 '16 at 19:34
  • I think you'll find your answer in this post : http://stackoverflow.com/questions/2330942/java-variable-number-or-arguments-for-a-method – Thomas W. Sep 15 '16 at 19:36
  • `ArrayList` work the best for me so I can't use an array – Takichiii Sep 15 '16 at 19:37
  • 1
    `Arrays.asList()` may help. – Mordechai Sep 15 '16 at 19:41
  • Try [Collections.addAll](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#addAll-java.util.Collection-T...-). – VGR Sep 15 '16 at 19:49
  • 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. – Andreas Sep 15 '16 at 20:12
  • `this.vehicles.addAll(Arrays.asList(vehicles));` – Jesper Sep 15 '16 at 20:21

1 Answers1

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.

Joe C
  • 15,324
  • 8
  • 38
  • 50