Java - 将 TreeSet转换为最有效的方法到一个字符串[]?
我正在这样做:
(String[]) myTreeSet.toArray();
但这在运行时给了我一个 ClassCastException 。
我唯一能想到的就是先创建一个数组,然后迭代 myTreeSet 中的每个元素并将其添加到数组中。看来一定还有比这更好的办法。有或我应该这样做吗?
谢谢。
I was doing this:
(String[]) myTreeSet.toArray();
but that gives me a ClassCastException at runtime.
The only thing I can think of doing is just making an array first and then iterating through each element in myTreeSet and adding it to the array. It seems like there must be a better way than this. Is there or should I just do this?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当使用 toArray() 时,会发生以下情况:使用 new Object[size] 分配一个新的对象数组,并且该数组中的每个元素将是对以下之一的引用你的字符串元素。即使实际上指向字符串,它也是一个
Object
类型的数组。当使用 toArray(T[] a) 时,会发生以下情况:使用 using 分配一个新的 T 数组
,并且数组中的每个数组都将是对您的字符串之一的引用,因为
a.getClass ().getComponentType
在您的情况下将返回String.class
。这次,它是一个 String 类型的数组。When using
toArray()
the following happens: a new Object array is being allocated by usingnew Object[size]
and each element from the array will be a reference to one of your strings element. Even if actually points to strings, it's an array with the typeObject
.When using
toArray(T[] a)
the following happens: a new T arrays is being allocated by usingand each from the array will be a reference to one of your strings because
a.getClass().getComponentType
will returnString.class
in your case. This time, it's an array with the type String.