简体   繁体   English

我是否必须将Java中已经通用的数组转换为通用类型

[英]Do i have to cast an already generic array in java to a generic type

Sorry for the wording but maybe code can be understood easier 措词很抱歉,但也许可以更容易理解代码

public class Generic<E> implements List<E>
{
    private static final int defaultSize = 10; //Default size
    private int maxSize; //Maximum size of list
    private int listSize; //Current # of items in list
    private int curr; //Position of current element
    private E[] listArray; //Array holding list elements
    Generic()
    {
        this(defaultSize);
    }
    /**
    * Create a new list object
    * @param siz Max # of elements list can contain
    */
    @SuppressWarnings("unchecked") //generic array allocation
    Generic(int size)
    {
        maxSize = size;
        listSize = curr = 0;
        listArray = (E[]) new Object[size]; //create listArray

My two questions are these: 我的两个问题是:

  1. The last line, when I create the list as an object of size size , why do I have to cast it as a generic array when it's initialized as a generic array already? 最后一行,当我将列表创建为大小为size的对象时,为什么在将其初始化为通用数组时,为什么必须将其转换为通用数组?

  2. Can the @SuppressWarnings("unchecked"); 可以@SuppressWarnings("unchecked"); be explained? 被解释? What it does I can see, but I have never seen the @SuppressWarnings on any of the pages in my Java book; 我可以看到什么,但是我从未在Java书籍的任何页面上看到@SuppressWarnings how can we start with @ ?? 我们如何以@ ??开始?

Sidenote - this code is straight from my Data Structures book and I'm trying to break it down to understand it. 旁注-此代码直接来自于我的数据结构书,我正尝试对其进行分解以理解它。

  1. You have to recast it as E[] because of type erasure : at runtime, every generic is treated as Object . 由于类型擦除 ,您必须将其重铸为E[] :在运行时,每个泛型都被视为Object You can't initialize listArray as new E[] . 您不能将listArray初始化为new E[]
  2. @SuppressWarnings is an annotation, basically extra information besides imperative code. @SuppressWarnings是一个注释,除命令性代码外,基本上是其他信息。

You have to supressed unchecked because otherwise the Java compiler will warn you when it encounters the potentially dangerous cast of Object[] to E[] . 您必须unchecked因为否则Java编译器会在遇到Object[]E[]的潜在危险转换时向您发出警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM