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

前端 未结 6 2151
粉色の甜心
粉色の甜心 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:11

    From Oracle tutorial [sic]:

    You cannot create arrays of parameterized types. For example, the following code does not compile:

    List[] arrayOfLists = new List[2];  // compile-time error
    

    The following code illustrates what happens when different types are inserted into an array:

    Object[] strings = new String[2];
    strings[0] = "hi";   // OK
    strings[1] = 100;    // An ArrayStoreException is thrown.
    

    If you try the same thing with a generic list, there would be a problem:

    Object[] stringLists = new List[];  // compiler error, but pretend it's allowed
    stringLists[0] = new ArrayList();   // OK
    stringLists[1] = new ArrayList();  // An ArrayStoreException should be thrown,
                                                // but the runtime can't detect it.
    

    If arrays of parameterized lists were allowed, the previous code would fail to throw the desired ArrayStoreException.

    To me, it sounds very weak. I think that any programmer with a sufficient understanding of generics, would be perfectly fine, and even expect, that the ArrayStoredException is not thrown in such case.

    Even more, most programmers will simply do:

    List arrayOfLists = (List) new List[2];
    

    which will put them in exactly the same risk of ArrayStoreException not thrown.

提交回复
热议问题