Arrays are low-level constructs you shouldn't use unless their component type is primitive or you really know what you are doing (e.g. you have a performance need, and you are fully aware of how hard it can be to determine if you truly do have a performance need).
I now want to create an array of cars from the values
No you don't. You want a List<Car>
or Collection<Car>
:
Collection<Car> justCars = cars.values();
// or, if you need list-specific stuff:
List<Car> justCars = new ArrayList<Car>(cars.values());
There's rather little arrays can do that lists cannot, but there's a lot that lists can do that arrays cannot.
But if you're somehow convinced you must have an array, this has nothing to do with lists; to convert a collection to an array, don't call toArray()
. Instead:
anyCollection.toArray(new Car[0]); // always 0
anyCollection.toArray(Car[]::new); // or this
i.e. cars.values().toArray(new Car[0])
does the job.