I’ve following queue class:
class Queue
{
private Object[] data;
private int numOfElements;
private int head;
private int tail;
Queue(int size)
{
if (size <= 0)
throw new IllegalArgumentException("Size must be greater or equals 0.");
data = new Object[size];
head = 0;
tail = 0;
numOfElements = 0;
}
void enqueue(Object obj)
{
data[tail] = obj;
tail = (tail + 1) % data.length;
if (numOfElements < data.length)
numOfElements++;
}
Object dequeue()
{
if (numOfElements == 0)
throw new EmptyQueueException();
Object dequeuedObject = data[head];
data[head] = null;
head = (head + 1) % data.length;
numOfElements--;
return dequeuedObject;
}
I call the method enqueue like this: test_queue.enqueue(new Event(arg1, arg2));
The Event object contains two integers which are set to the values of arg1 and arg2. How does data.length inside method enqueue work?
How can it get the size of the Event object correctly?
data.lengthreturns you the number of elements ofdata, which is your array (instance field). You might be looking for something like C’ssizeof, but as far as I know Java does not provide it.Why would you want it? As you store only references to objects on the heap in your array, each array element’s size is basically constant.
By the way, have you thought of using a linked list or a built-in queue implementation (
Queue<E>) instead of an array?