Convert a generic list to an array

前端 未结 13 1290
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 17:13

I have searched for this, but unfortunately, I don\'t get the correct answer.

class Helper {
    public static  T[] toArray(List list) {
           


        
13条回答
  •  庸人自扰
    2020-12-05 17:45

    I use this simply function. IntelliJ just hates that type cast T[] but it works just fine.

    public static  T[] fromCollection(Class c, Collection collection) {
        return collection.toArray((T[])java.lang.reflect.Array.newInstance(c, collection.size()));
    }
    

    And call looks like this:

    Collection col = new ArrayList(Arrays.asList(1,2,3,4));    
    fromCollection(Integer.class, col);
    

提交回复
热议问题