“Cannot create generic array of ..” - how to create an Array of Map?

前端 未结 6 2141
粉色の甜心
粉色の甜心 2020-11-28 11:39

I would like to use simpleJdbcInsert class and executeBatch method

public int[] executeBatch(Map[] batch)

http://stati

6条回答
  •  一生所求
    2020-11-28 12:33

    I have had some difficulty with this, but I have figured out a few things that I will share as simply as possible.

    My experience with generics is limited to collections, so I use them in the class definitions, such as:

    public class CircularArray {
    

    which contains the data member:

    private E[] data;
    

    But you can't make and array of type generic, so it has the method:

    @SuppressWarnings("unchecked")
    private E[] newArray(int size)
    {
        return (E[]) new Object[size];  //Create an array of Objects then cast it as E[]
    }
    

    In the constructor:

    data = newArray(INITIAL_CAPACITY);  //Done for reusability
    

    This works for generic generics, but I needed a list that could be sorted: a list of Comparables.

    public class SortedCircularArray> { 
    //any E that implements Comparable or extends a Comparable class
    

    which contains the data member:

    private E[] data;
    

    But our new class throws java.lang.ClassCastException:

    @SuppressWarnings("unchecked")
    private E[] newArray(int size)
    {
        //Old: return (E[]) new Object[size];  //Create an array of Objects then cast it as E[]
        return (E[]) new Comparable[size];  //A comparable is an object, but the converse may not be
    }
    

    In the constructor everything is the same:

    data = newArray(INITIAL_CAPACITY);  //Done for reusability
    

    I hope this helps and I hope our more experienced users will correct me if I've made mistakes.

提交回复
热议问题