3 Replies - 2730 Views - Last Post: 10 February 2012 - 11:37 AM Rate Topic: -----

#1 Hiatus  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 81
  • Joined: 27-May 09

Error: Generic Array Creation

Posted 10 February 2012 - 09:57 AM

Hey all, I'm trying to make this iterator program and to add to my already extremely high level of confusion, I got this error when compiling my code.

import java.util.Iterator;
@SuppressWarnings("unchecked")
public class Queue<Item> implements Queueable<Item>, Iterable<Item> {
    private int CAP; // Initial capacity of the Queue
    private Item[] A;    // underlying array in which to store elements
    private int next;   // next available slot at rear of Queue
    private int first;  // slot at head of Queue
    private int size;   // size of Queue
   
    public Queue() {
        A = new Item[10]; 
        next = 0; 
        first = 0; 
        size = 0; 
    } 



Anyone give me some advice as to how to fix this?

Is This A Good Question/Topic? 0
  • +

Replies To: Error: Generic Array Creation

#2 ianian112  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 119
  • View blog
  • Posts: 378
  • Joined: 28-November 09

Re: Error: Generic Array Creation

Posted 10 February 2012 - 10:15 AM

try
A = (Item[])new Object[10];
Was This Post Helpful? 0
  • +
  • -

#3 Hiatus  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 81
  • Joined: 27-May 09

Re: Error: Generic Array Creation

Posted 10 February 2012 - 10:22 AM

View Postianian112, on 10 February 2012 - 10:15 AM, said:

try
A = (Item[])new Object[10];


I fucking love you
Was This Post Helpful? 0
  • +
  • -

#4 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2720
  • View blog
  • Posts: 11,440
  • Joined: 20-September 08

Re: Error: Generic Array Creation

Posted 10 February 2012 - 11:37 AM

That (although it's a kind of a workaround) is not the way to implement the creation of your array, since you might as well not use generics if you're going to ignore them and typecast. The way to create a generic array is through reflection. Because of type erasure though, it gives you a little bit of a problem, but the workaround would be to create the array 'lazily' from the parameter to a method such as enqueue

There's an example of generic array creation here

http://technojeeves....a-generic-array
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1