Skip to content
Advertisement

java.lang.ArrayStoreException on List to Array

When I use the toArray function from Java util I get an ArrayStoreException with no message. I implemented the absolute same code a year ago in pretty much the same Model and it works there, the query works fine and returns [1,2] from the DB. here is the code I use:

List<?> firstColumn = Base.firstColumn(query, paramList.toArray());
return firstColumn.toArray(new Integer[0]);

I dont understand why it would not show an Error Message, without it I was lost for days now, hence I turned to you guys, thanks in Advance!

Advertisement

Answer

The problem is that your firstColumn list does not contain Integer instances. Since you claim that it contains [1,2], probably your list contains Byte, Short, or Long instances. Java will perform some automatic conversions on primitive types, but it does not do that for wrapper objects or arrays. So you have two options:

  • Return an array of the correct type:

    return firstColumn.toArray(new Short[0]); // or Byte[0], or Long[0]
    
  • Or, if that is not an option, perform the conversion to integers yourself:

    return firstColumn.stream().map(x -> ((Number)x).intValue()).toArray(Integer[]::new);
    
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement