简体   繁体   English

错误:<identifier> 制作 generics 数组时预期</identifier>

[英]error: <identifier> expected when making array of generics

I am trying to create an array of generics by type casting, but everything I've tried has resulted in error: <identifier> expected .我正在尝试通过类型转换创建一个 generics 数组,但是我尝试的所有操作都导致error: <identifier> expected The task is to make an array based Deque.任务是创建一个基于数组的 Deque。 I've tried:我试过了:

  • @suppresswarning("unchecked") @suppresswarning("未选中")
  • Random rewriting of the code随机重写代码

Here is a snippet of the code这是代码片段

public class dequeCyclic<E> implements Deque<E> {
private int first;
private int last; 
private E[] deque;

public dequeCyclic(int size){
    @SuppressWarning("unchecked")
    deque =(E[]) new Object[size];
    first = -1; 
    last = -1; 
}   

Any help would be greatly appreciated.任何帮助将不胜感激。

You can't put @SuppressWarning on statements.您不能将@SuppressWarning放在语句上。 They are only allowed on declarations, so you have three options, either annotate the class:它们只允许在声明中使用,因此您有三个选项,或者注释 class:

@SuppressWarning("unchecked")
public class dequeCyclic<E> implements Deque<E> {

or the constructor:或构造函数:

@SuppressWarning("unchecked")
public dequeCyclic(int size) {
    deque =(E[]) new Object[size];
    first = -1; 
    last = -1; 
}

Or create a local temporary variable:或者创建一个局部临时变量:

public dequeCyclic(int size) {
    @SuppressWarning("unchecked")
    E[] temp =(E[]) new Object[size];
    deque = temp;
    first = -1; 
    last = -1; 
}

The last one with the temporary variable should be prefered, because the first and second variant suppress all unchecked warnings inside of them.应该首选带有临时变量的最后一个,因为第一个和第二个变体会抑制其中的所有未经检查的警告。 Which is generally more harmful than useful.这通常弊大于利。

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

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