转换为 Message 数组
在我的时区,下午好。
我有一个“简单”的问题。
我有一个 ArrayList ,但是当我使用 ArrayList 对象中的 toArray 方法将此 ArrayList 转换为数组并将其转换为 Message[] 时,它会抛出 java.lang.ClassCastException 吗? Message 类属于包“javax.mail.Message” 代码片段:
List<Message> messageList = new ArrayList<Message>();
--code to fullfill the List
(Message[]) messageList.toArray();
抛出和异常: 线程“main”中的异常 java.lang.ClassCastException: [Ljava.lang.Object;无法转换为 [Ljavax.mail.Message;
谁能解释一下为什么会发生这种情况?
致以最诚挚的问候
Good Afternoon in my timezone.
I have a "simple" question.
I have an ArrayList , but when i transform this ArrayList to array using the method toArray from the ArrayList object and cast it to Message[] it throws an java.lang.ClassCastException ? The Message class belongs to package "javax.mail.Message"
Snippet of code :
List<Message> messageList = new ArrayList<Message>();
--code to fullfill the List
(Message[]) messageList.toArray();
Throws and exception:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljavax.mail.Message;
Can anyone explain me why this happen ?
With the best regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
虽然
Object
可能会被转换为Message
(有时),但即使所有对象都是消息,您也无法将对象数组转换为消息数组,就像您的情况一样。这与无法将
ArrayList
考虑 <代码>toArray(T[])方法。
Although an
Object
may be casted toMessage
(sometimes) you cannot cast an array of Objects to array of Messages even if all the objects are Messages, as in your case.This is similar (but not the same) to the fact that you cannot cast
ArrayList<Object>
toArrayList<Message>
.Consider the
toArray(T[])
method.您应该创建一个
Message
数组,然后将其传递给 toArray()。您正在调用的方法 确实返回一个Object
数组,因此出现类转换异常。即使第二个对象扩展了第一个对象,也不能将一种对象类型的数组转换为另一种对象类型的数组。检查文档
You should create an array of
Message
and then pass it to the toArray(). The method you are calling does return an array ofObject
, hence the classcast exception. You cannot cast an array of one object type to an array of another, even if the second object extends the first.Check the documentation here
toArray()
方法创建一个无法强制转换的Object[]
类型的数组。为了创建具有正确类型的数组,您必须告诉 toArray() 方法要使用哪种类型:The
toArray()
method creates an array of typeObject[]
which cannot be cast. In order to create an array with the correct type, you have to tell thetoArray()
method which type to use: