1

See the following mapping

public class SomeClass {

    private Integer someField;

}

When i call the following query

select someField, count(*) from SomeClass inner join OtherClass... group by ...

And i proccess the query as follows

Map<Integer, Integer> result = new HashMap<Integer, Integer>();

List<Object> objectList = query.list();
for(Object object: objectList) {
    Object [] objectArray = (Object []) object;

    result.put((Integer) objectArray[0], (Integer) objectArray[1]);
}

I get ClassCastException: can not convert Long to Integer

Question: what should i do to retrieve the values returned by the HQL as Integer instead of Long ????

1
  • Both answers are correct! (+1) Trank you! Commented Feb 23, 2010 at 15:40

2 Answers 2

3

If you don't know which it will be (Integer or Long), you can cast to Number and call intValue() or longValue(). This way an Integer or a Long will work.

result.put((Integer) objectArray[0], ((Number) objectArray[1]).intValue() );

The small downside with this is you end up unboxing the Number and reboxing it to put in the map.

Sign up to request clarification or add additional context in comments.

Comments

1

I guess the second column in the result - i.e. count(*) returns Long. You can get its int value by ((Long) objectArray[1]).intValue()

Or (as suggested), better change your map to Map<Integer, Long>, so that no information is eventually lost.

1 Comment

Note that you may lose information. Rather just use Long instead of Integer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.