I am having trouble understanding the nuances of generics, interfaces, and arrays and how to use them together. I have an assignment for an intermediate Java class. The assignment is as follows:
- Create a generic class SimpleQueue that implements Queue
- Use a constructor to initialize an array with 5 slots.
- Use of ArrayList not allowed
- We must be able to increase the size of the array if it gets filled
The problem I'm having is the with the initialization of the array. Here's the code I have:
import java.util.Collection;
import java.util.Iterator;
import java.util.Queue;
public class SimpleQueue<E> implements Queue<E>{
private E myQueue[];
//Constructor with no arguments.
public SimpleQueue() {
myQueue = new [5];
System.out.println("A queue with length " + myQueue.length + " was created.");
}
}
Eclipse complains by saying that we can't create a generic array. I've managed to get it to work by doing this:
private Object myQueue[] = Object[5];
...but I feel like this defeats the purpose of using generics. Am I misunderstanding the use of generics? Pointers would be greatly appreciated!
This is the code I'm using to test my generic class as I'm working:
public class SimpleQueueTester {
public static void main(String [] args) {
SimpleQueue<String> myStringQueue = new SimpleQueue<>();
SimpleQueue<Integer> myIntegerQueue = new SimpleQueue<>();
}
}
Disclaimer: Please don't think I want my homework done for me. I'm just stuck at this point and I figured this would be the best place to ask. Thanks!
Edit: I took some of your suggestions and now my code looks like this:
public class SimpleQueue<E> implements Queue<E>{
private E[] myQueue;
@SuppressWarnings("unchecked")
//Constructor with no arguments.
public SimpleQueue() {
//This was changed. What does (E[]) do exactly?
this.myQueue = (E[]) new Object[5];
System.out.println("A queue with length " + this.myQueue.length + " was created.");
}
}
Thank you for you suggestions! You guys are awesome.