0

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.

Thomas
  • 80,843
  • 12
  • 111
  • 143

1 Answers1

0

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.

Lino
  • 17,873
  • 4
  • 40
  • 57