in java中的通用数组:探索协方差和type Erasure
一个潜在的解决方案是使用array.newinstance()方法: ... hashtable =(compopable [])array.newInstance(compobable.class,tablesize); 这种方法允许您创建一系列通用类型的supertype(在这种情况下可比较),但重要的是要注意,此数组不具有所需的通用类型。 Generics?
While there are workarounds, using arrays with generics is generally discouraged due to:Type Safety Concerns:
Casting an Object array to a generic array can lead to type safety issues since arrays are covariant and generics use type erasure.
Portability and Maintainability: Different Java Virtual Machines (JVMs) may handle type erasure differently, making the behavior less portable and more difficult to maintain.
Alternative: ArrayList
A more suitable option is to use ArrayList,它提供了一种高效且类型的安全方法来管理通用对象的集合。 ArrayLists提供了仿制药的灵活性,并避免了与数组和通用物相关的潜在陷阱。免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3