Cast to an array of Message
-
29-10-2019 - |
문제
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
해결책
You should create an array of Message
and then pass it to the toArray(). The method you are calling does return an array of Object
, 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.
Message[] messages = new Message[messageList.size()];
messageList.toArray(messages);
Check the documentation here
다른 팁
Although an Object
may be casted to Message
(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>
to ArrayList<Message>
.
Consider the toArray(T[])
method.
The toArray()
method creates an array of type Object[]
which cannot be cast. In order to create an array with the correct type, you have to tell the toArray()
method which type to use:
(Message[]) messageList.toArray(new Message[messageList.size()]);