简体   繁体   中英

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 . The task is to make an array based Deque. I've tried:

  • @suppresswarning("unchecked")
  • 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. They are only allowed on declarations, so you have three options, either annotate the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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