0

I have a hashmap setup like this:

cars = new HashMap<Integer, Car>();

I now want to create an array of cars from the values:

Car[] carArray = (Car[])cars.values().toArray();

But it says I cannot cast

java.lang.Object; cannot be cast to Car

What am i doing wrong here?

WDUK
  • 1,412
  • 1
  • 12
  • 29

2 Answers2

0

You can pass a function to construct an array of the correct type. toArray() without any arguments always returns an array of Objects.

Car[] carArray = cars.values().toArray(Car[]::new);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

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.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • Ah i was using array because it had a sort() method, when i used ArrayList i couldn't simply do `.sort()` and have it call my compareTo method which i had implemented with `Comparable` interface. But i'll go back to array list and figure out how to use the sort method. – WDUK Mar 29 '23 at 04:15
  • arrays do not have a sort method. There's `Arrays.sort()`. If you want to sort a list on its natural order, `list.sort(Comparator.naturalOrder())` is roughly equivalent to `Arrays.sort(arr);`. – rzwitserloot Mar 29 '23 at 11:29