将HashSet转换为数组时抛出ArrayStoreException [英] ArrayStoreException thrown when converting HashSet to array

查看:118
本文介绍了将HashSet转换为数组时抛出ArrayStoreException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下代码:

    int[] ho = new int[10];
    ho[0]= 1;
    ho[2]= 1;
    ho[4]= 5;

    HashSet<Integer> hs = new HashSet(Arrays.asList(ho));

    Integer[] a = hs.toArray(new Integer[hs.size()]);

这段代码对我来说很有意义,但是当我运行它时会抛出一个ArrayStoreException.这是为什么? HashSet是一组Integer s,输出数组也是如此.

This code makes perfect sense to me, but it throws an ArrayStoreException when I run it. Why is that? The HashSet is a set of Integers, and so is the output array.

推荐答案

ArrayStoreException:如果指定数组的运行时类型不是该集合中每个元素的运行时类型的超类型"

ArrayStoreException: "if the runtime type of the specified array is not a supertype of the runtime type of every element in this set"

ArrayStoreException表示试图将错误类型的对象存储到对象数组中.

ArrayStoreException is thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.

尝试切换int[] to Integer[]

这篇关于将HashSet转换为数组时抛出ArrayStoreException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆