-2

I want to extract the Integer values of a HashMap to an Integer array, discarding the keys. Java demands the array is of type Object. As a Java beginner, I also failed to find a way to convert "Object" to Integer.

The expected output is sorted array of the values: {3, 2, 1}.

import java.util.*;

public class test {
  public static void main(String [] args) {
    Integer[] number = {1, 2, 3, 3, 1, 1};
    HashMap<Integer, Integer> dist = new HashMap<>();
    Integer count;
    for (Integer i : number) {
      count = 1;
      if (dist.containsKey(i))
        count += dist.get(i);
      dist.put(i, count);
    }
    // Program fails below, *Object[] cannot be converted to Integer[]*. 
    Integer[] distArr = dist.values().toArray(); // Works if I replace Integer with Object
    distArr.sort(); // This fails on Object[]
    // ...
  }
}
s_baldur
  • 29,441
  • 4
  • 36
  • 69
  • 1
    Please look at the [documentation](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/Collection.html#toArray(T%5B%5D)). `toArray` can take an argument where you can define the type of the array. – QBrute Jan 22 '22 at 13:38

1 Answers1

1

You have to tell toArray() to what type of array it should create:

Integer[] distArr = dist.values().toArray(Integer[]::new)

or provide a "an existing array that just need to be filled" (this is the only-style way for Java 8 and lower):

Integer[] distArr = dist.values().toArray(new Integer[dist.values().size()])

Or if you don't mind that the array is recreated you can simply provide an empty "example array":

Integer[] distArr = dist.values().toArray(new Integer[0])
Robert
  • 39,162
  • 17
  • 99
  • 152