Why are there exceptions to the following java code?

Why do I get exceptions

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 codes?

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();
        }
}

Can object [] be returned to integer [] because the keyset contains integers? What is a quick alternative to copying keysets to an array of integers?

Solution

use

Integer[] keys = h.keySet().toArray(new Integer[h.keySet().size()]);

Passing an array of the same size as the keyset is indeed the best method, because Java will use the given array to store all the values of the keyset If the given array is different from the keyset size, Java must create a new array to fit the keyset size The first array passed will never be used and will occupy memory until the garbage collector allocates it again

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>