两种方法创建通用阵列 [英] Two methods for creating generic arrays

查看:89
本文介绍了两种方法创建通用阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经学会了以下两种方法来创建通用阵列。

I've learned following two methods for creating generic arrays.

一个是

@SuppressWarnings("unchecked")
static <T> T[] array1(final Class<T> elementType, final int size) {

    return (T[]) Array.newInstance(elementType, size);
}

和另一个是

static <T> T[] array2(final Class<T[]> arrayType, final int size) {

    return arrayType.cast(Array.newInstance(arrayType.getComponentType(), size));
}

哪个更好?他们是相同的(内部)?任何情况下,其实错了?

Which is better? Are they same (internally)? Is any case actually wrong?

推荐答案

在幕后,这两个有效的做同样的事情,只是在选项1你传递 T 的类对象,并在选项2你传递 T [] 的类对象。

Behind the scenes, the two do effectively the same thing, except that in option 1 you're passing in T's class object and in option 2 you're passing in T[]'s class object.

我preFER选项1,因为它是更短,更易于阅读。话又说回来,这是一样的 Array.newInstance 带投加,所以我不知道你的方法添加了很多价值。 : - )

I prefer option 1 because it's shorter and easier to read. Then again, it's the same as Array.newInstance with a cast added, so I'm not sure that your method adds a lot of value. :-)

这篇关于两种方法创建通用阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆