Reputation: 4562
I am getting following error while trying to execute following code snippets. Please let me know what are the possible reasons of getting this error.
List list = .... ;
for(Object obj:list)
{
Object[] myObj = (Object[])obj;
Long lg = ...;
if(myObj[1]!=null){
lg = ((BigDecimal)myObj[1]).longValue();
}
java.lang.ClassCastException
at java.lang.Class.cast(Class.java:...)
Upvotes: 0
Views: 252
Reputation: 6527
Because myObj[1]
is not a BigDecimal
.
A ClassCastException ocurrs when you try to cast an instance of an Object to a type that it is not.
Upvotes: 2
Reputation: 15418
List<BigDecimal[]>
myObj
is not likely a BigDecimal[]
object, hence a ClassCastException
can occur.Upvotes: 2
Reputation: 95978
By that explicit cast, you're telling the compiler to trust you that you know what you're doing. Thus, your program compiles but crashes because.. myObj[1]
is not a BigDecimal
, you fooled the compiler and now his best friend (the JVM) is angry.
Upvotes: 3
Reputation: 12890
You are trying to cast an unSupported Object type to a BigDecimal
object. i.e. myObj[1] is not a BigDecimal instance.
ClassCastException
documenation says that
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
Upvotes: 1
Reputation: 68887
The reason is that obj
is not an array or that myObj[1]
is not a BigDecimal.
To debug this, you can add these lines:
System.out.println(obj.getClass());
System.out.println(myObj[1].getClass());
This will tell you what it actually is.
Upvotes: 3