简体   繁体   中英

How to convert Array datatype(H2 database) to java List<Long>?

I tried this

        Array a = resultSet.getArray("IDS");
        Object[] idsArray = (Object[]) a.getArray();

        List<Long> idsList = new ArrayList<>();
        for(Object obj : idsArray) {
            idsList.add((Long) obj);   -----> (java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer)
        }

It's throwing exception. Then if I change the list to Integer and cast to Integer, it's throwing java.lang.Integer cannot be cast to java.lang.Long (exception just like above but reverse)

More Details: Array datatype has BIGINT values in the H2 database table

Any solutions for this?

This is because you cannot cast Long to Integer. Because you are using an Array of Objects and that objects are Integers. You need to tell to your code that that Object that you are getting is an Integer and if you want to cast to Long you only need to do this.

Object[] idsArray = {new Integer(1)};
        List<Long> idsList = new ArrayList<>();
        for(Object obj : idsArray) {
            idsList.add(new Long((Integer) obj));
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM