I'm currently t开发者_StackOverflow社区rying to populate an array of of objects of the type Stipulations
which is a class which is an
public abstract interface
My method of populating this array is as follows where popStipAttr
is a simple switch statement.
public static Stipulations[] popStipArr(ZASAllocation zasAlloc)
{
//ArrayList<String> s = new ArrayList<String>();
ArrayList<Stipulations> stipAL = new ArrayList<Stipulations>();
for(int i = 0; i < NoStip; i++)
{
stipAL.add(popStipAttr(i,zasAlloc));
}
Stipulations[] StipArr = (Stipulations[]) stipAL.toArray();
return StipArr;
}
However I get the error about casting:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lc.Stipulations;
What exactly am I doing wrong here I created the arraylist of the same type, why would coverting it to an array of that type throw this?
ArrayList.toArray
returns an Object[]
(which, as stated in the message, can't be cast to Stipulations[]
). ArrayList.toArray(T[] a)
however, returns a T[]
. Thus, change
Stipulations[] StipArr = (Stipulations[]) stipAL.toArray();
to
Stipulations[] StipArr = (Stipulations[]) stipAL.toArray(new Stipulations[0]);
^^^^^^^^^^^^^^^^^^^
Oh, right. Just realized what may have caused the confusion. The leading [
in [Ljava.lang.Object;
indicates that it is an array. Same for [Lc.Stipulations;
. Perhaps that's why you wrote Casting from type object to a class as title :-) Now you know anyway :-)
What you are doing in
Stipulations[] StipArr = (Stipulations[]) stipAL.toArray();
is calling the method on the java.util.List class
Object[] toArray();
which is returning you an Object[] which cant be cast to your Stipulations[]
What you want to be calling is the method on java.util.List
<T> T[] toArray(T[] a);
which will return you the array with your type. So try
Stipulations[] StipArr = stipAL.toArray(new Stipulations[stipAL.size()]);
It is a strange syntax which tends to pollute the code and for this reason and a few others I always try to use Lists where possible and never convert to and from Arrays unless absolutely necessary like an external API not under my control requires it
精彩评论