0

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?

arge
  • 635
  • 1
  • 7
  • 16
  • 3
    `data` is just an array (with a length), the size of Event is irrelevant, so what exactly do you mean? – harold Apr 30 '12 at 13:42
  • Look here for an explanation on `length` field: http://stackoverflow.com/questions/5950155/java-arrays-length – maksimov Apr 30 '12 at 13:43

2 Answers2

2

data.length returns you the number of elements of data, which is your array (instance field). You might be looking for something like C's sizeof, 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?

Matthias Meid
  • 12,455
  • 7
  • 45
  • 79
  • Ok, thx for the explanation. I can't use a built-in queue implementation, because I don't have the interface available(Mobile Java app) – arge Apr 30 '12 at 13:51
  • You are welcome. This sample implementation may help you too: http://www.java2s.com/Code/Java/Collections-Data-Structure/SimpleQueueFIFObasedonLinkedList.htm – Matthias Meid Apr 30 '12 at 14:13
1

data.length will just return the size of the static array data, so in this case the size you passed to the Queue constructor. As for the enqueue method, it doesn't need the size of the Event elements, as the data array doesn't store the elements themselves, but references to the elements, and the references are of a fixed size, regardless of if the event object fields (the two integers you mentioned) have actually been set.

Marcus Mathioudakis
  • 837
  • 1
  • 6
  • 19