如何在Java中创建类型安全通用阵列? [英] How to create a type safe generic array in java?

查看:165
本文介绍了如何在Java中创建类型安全通用阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在Java中创建一个通用的阵列通常保持在Java提供的类型安全。

I want to create a generic array in java maintaining the type safety usually offered by Java.

我用这code:

class Stack<T> { 

private T[] array = null;
public Stack(Class<T> tClass, int size) {
   maximumSize = size;
   // type unsafe
   //array = (T[])new Object[maximumSize];

   this.array = (T[])java.lang.reflect.Array.newInstance(tClass,maximumSize);
}

这是code型安全吗?答如果是这样,为什么呢?为什么如果它的类型是安全的,我需要一个投?

is this code type safe? ans if so, why? why if it is type safe I need a cast?

推荐答案

的<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Array.html#newInstance%28java.lang.Class,%20int...%29\"><$c$c>Array.newInstance(..)方法对象的返回类型。因此,你不能直接将其分配到比对象其他任何东西。因此,您需要一个转换。

The Array.newInstance(..) method has a return type of Object. As such, you cannot directly assign it to anything other than Object. You therefore need a cast.

该方法委托给本地方法,它

创建一个具有指定的组件类型和长度

Creates a new array with the specified component type and length

因此​​,它是创造类型的数组 T

Therefore it is creating an array of type T.

该类型安全,假设阵列声明为

The type safety, assuming array is declared as

T[] array;

,由类和LT保证; T&GT; 参数,并使用相同类型的变量中投

, is guaranteed by the Class<T> parameter and the cast using the same type variable.

您应该添加

@SuppressWarnings("unchecked")

带有注释解释你的源$ C ​​$ C以上的原因。总是评论为什么投他的警告,你燮pressing是安全的。

with a comment explaining the above reason in your source code. Always comment why a cast whose warning you are suppressing is safe.

这篇关于如何在Java中创建类型安全通用阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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