Why does I get an exception
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
at Main.main(Main.java:12)
for the following code?
import java.util.Set;
import java.util.HashMap;
public class Main
{
public static void main(String args[])
{
HashMap<Integer, Double> h = new HashMap<Integer,Double>();
h.put(1, 2.2);
Integer[] keys = (Integer[])h.keySet().toArray();
}
}
Shouldn’t it be possible to cast the Object[] returned to Integer[], since the key set contains integers? What is a fast alternative to copy the key set to an integer array?
Use
Passing an array of the same size as the keyset is indeed the best way because Java will use the given array to store all the values of the keyset. If the given array is not of the same size as the keyset, Java will have to create an entirely new array to fit the size of the keyset. The passed first array will never be used, it will just be taking up memory until the garbage collector allocates it again.