Java - 将 TreeSet转换为最有效的方法到一个字符串[]?

发布于 2025-01-04 21:48:40 字数 206 浏览 1 评论 0原文

我正在这样做:

(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

坦然微笑 2025-01-11 21:48:40
String[] result = myTreeSet.toArray(new String[myTreeSet.size()]);
String[] result = myTreeSet.toArray(new String[myTreeSet.size()]);
破晓 2025-01-11 21:48:40

当使用 toArray() 时,会发生以下情况:使用 new Object[size] 分配一个新的对象数组,并且该数组中的每个元素将是对以下之一的引用你的字符串元素。即使实际上指向字符串,它也是一个 Object 类型的数组。

当使用 toArray(T[] a) 时,会发生以下情况:使用 using 分配一个新的 T 数组

java.lang.reflect.Array
              .newInstance(a.getClass().getComponentType(), size) 

,并且数组中的每个数组都将是对您的字符串之一的引用,因为 a.getClass ().getComponentType 在您的情况下将返回 String.class 。这次,它是一个 String 类型的数组。

When using toArray() the following happens: a new Object array is being allocated by using new 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 type Object.

When using toArray(T[] a) the following happens: a new T arrays is being allocated by using

java.lang.reflect.Array
              .newInstance(a.getClass().getComponentType(), size) 

and each from the array will be a reference to one of your strings because a.getClass().getComponentType will return String.class in your case. This time, it's an array with the type String.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文