sonan
sonan

Reputation: 111

Postgres smallint[] into java short[] array

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.

Upvotes: 1

Views: 1652

Answers (1)

Mureinik
Mureinik

Reputation: 312086

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();
}

Upvotes: 2

Related Questions