0

I have an assignment in which I have a queue (from the class ArrayQueues) for which I am supposed to write a method in another class (Queues) that splits the queue into two. The method, split(Queue queue), takes the queue and returns another queue with half the items of the first queue, but it does not simply take the first half or second half. It takes every other item in the original queue and distributes the items evenly. This is how I am going about it:

public class Queues{
public static <E> Queue<E> split(Queue<E> queue){
    Queue<E> queue1 = new ArrayQueue<>(queue.capacity());
    Queue<E> queue2 = new ArrayQueue<>(queue.capacity());
    int size = queue.size();//I did this because the size of queue changes after every iteration due to it being dequeued
    for(int i = 0; i < size;i++){
        if(i%2==0){
            queue2.enqueue(queue.dequeue());//adds item from queue to queue2 and removes that item from queue
        }else{
            queue1.enqueue(queue.dequeue());//add item from queue to queue1 and removes item from queue
        }
    queue = queue1;
    return queue2;
    }
}

The result I get is queue2 and queue1 both have the appropriate items (every other item from queue). However, the original queue is now empty, and I understand that it would be since I have been dequeueing it. But I set

queue = queue1

Why is it empty even after I set it to queue1?

1 Answers1

1

queue is a local variable , so you can't use it outside the method unless you return it's value.

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
  • Thanks. So I am trying to split queue equally into a new queue and the original queue. Any suggestions on how to do this from what I have? Or am I going about it the wrong way? – user5362867 Nov 07 '15 at 04:53
  • call queue.clear(), then queue.addAll(queue1). That should do it. – Chicodelarose Nov 07 '15 at 05:39