【问题标题】:How do I set a generic object in my array to 0/null?如何将数组中的通用对象设置为 0/null?
【发布时间】:2015-02-19 12:36:40
【问题描述】:

我有一个数组,在我的类声明中包含泛型类型的对象(稍后,我将添加<Integer> 类型对象)。我想删除 currentSize 处的索引(这是一个 int)。 Eclipse 抱怨说“类型不匹配:无法将 int 转换为 E”关于该行

list[currentSize] = null;

这是我的代码:

...

private int currentSize, maxCapacity;

...

public ArrayABC(){
        currentSize = 0;
        maxCapacity = 20;
        list = (E[]) new Object[maxCapacity];
}

...

public E removeLast(){
        if(currentSize == 0)
            return null;

        list[currentSize] = null;
        currentSize--;
        return list[currentSize];
}

还要注意,在我尝试将 list[currentSize] 分配为返回值之后。这样做时我是否必须将其转换为<E>(代码的最后一行)?

我想一个更好的说法是,如何在 location = currentSize 处销毁对象?

提前感谢您的帮助和支持!

【问题讨论】:

  • 为什么不使用带有泛型的列表而不是数组?
  • 不幸的是,我必须这样做
  • 你能发布一个可编译的例子吗? IE。包括周围的类和使用的属性声明。

标签: java arrays oop generics


【解决方案1】:

这完全取决于您的 list 是如何声明的。 此外,由于您将其转换为类型参数 E,因此您必须在类声明中的某处使用此类型参数,如下所示:<E>

下面为我编译就好了:

public class ArrayABC<E> {

  private int currentSize, maxCapacity;
  private E[] list;

  public ArrayABC(){
          currentSize = 0;
          maxCapacity = 20;
          list = (E[]) new Object[maxCapacity];
  }

  public E removeLast(){
          if(currentSize == 0)
              return null;
          list[currentSize] = null;
          currentSize--;
          return list[currentSize];
  }
}

唯一的障碍是 Eclipse 突出显示:

list = (E[]) new Object[maxCapacity];

作为不安全访问的警告,但由于类型擦除,没有干净的方法来创建任何类型为 E 的对象的实例。

【讨论】:

    猜你喜欢
    • 2018-11-05
    • 2012-10-18
    • 2012-11-30
    • 2016-03-17
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2010-10-09
    相关资源
    最近更新 更多