1

I have a database table in PostgreSQL with a column named 'data' and type: smallint[]

I am trying to save data from the query to a java short[] and I am getting the following exception:

java.lang.ClassCastException: class [Ljava.lang.Integer; cannot be cast to class [I ([Ljava.lang.Integer; and [I are in module java.base of loader 'bootstrap')"

My implementation:

String sql = "SELECT * FROM table"
res = executeQuery(stmt, temp);

        ArrayList<VO> vos = new ArrayList<>();
        while (res.next()) {
            VO vo = new VO();
            Array ar = res.getArray("data");
            // vo has a private member data : short[]
            vo.setData((short[]) ar.getArray());
        }

Exception is thrown @vo.setData((short[]) ar.getArray());, where I am trying to cast the java.sql.Array into a short[] array.

1 Answer 1

2

from the error message, it seems getArray returns an Integer[]. You'll have to convert it to a short[] manually:

Integer[] arr = (Integer[]) ar.getArray();
short[] data = new short(arr.length);
for (int i = 0; i < arr.length; ++i) {
    data[i] = arr[i].shortValue();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer. That really worked. I was stuck for many hours :p . I thought I had tried this solution.

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.