Nidheesh
Nidheesh

Reputation: 4562

java.lang.ClassCastException-((BigDecimal)myObj[1]).longValue()

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

Answers (5)

Rakesh KR
Rakesh KR

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

Sage
Sage

Reputation: 15418

  1. Never work with Raw type Collection: declare your collection with proper Generic types of your case: List<BigDecimal[]>
  2. myObj is not likely a BigDecimal[] object, hence a ClassCastException can occur.

Upvotes: 2

Maroun
Maroun

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

Keerthivasan
Keerthivasan

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

Martijn Courteaux
Martijn Courteaux

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

Related Questions