0

I need to create a second ArrayQueue of the same type that is passed in, so I can items in the Queue. I cannot instantiate the second ArrayQueue unless I make it of a specific class which defeats the purpose of the generic and fails the tests when the test switches from Integer, Character, Object, or Boolean.

Javadoc(https://s3.amazonaws.com/mimirplatform.production/files/820e6d35-fa73-4c54-8f0a-e97159bf86c1/ArrayQueue_methods.PNG)

The test cases pass in an ArrayQueue to operate on, but the code needs to create a second ArrayQueue of the same type that is passed in. I tried using as the type but it does not compile.

Example

If … entering the adjacentPairs method the queue were front [ 12, 34, 56, 78, 90 ] back

Then … exiting the adjacentPairs method the queue would be front [ 34, 12, 78, 56, 90 ] back

public class Swap
{
    public static void adjacentPairs (ArrayQueue arr) throws NullPointerException
    {
        if(arr.isEmpty())
        {
            return;
        }
        int n = arr.size();//finding size
        for(int i=0;i<n;i=i+2)
        {
            if(i+1<n)
            {//swapping adjacentpairs
                ArrayQueue a = new ArrayQueue(????, n);//to swap
                a.enqueue(arr.dequeue());
                arr.enqueue(arr.dequeue());
                arr.enqueue(a.dequeue());
            }
            else
                arr.enqueue(arr.dequeue());
        }

    }
}
  • 1
    You are using the raw type. Use `ArrayQueue` instead. – Michael Jul 20 '19 at 19:14
  • 1
    To enhance @Michael comment: See [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Turing85 Jul 20 '19 at 19:15
  • It is perhaps worth pointing out that there is no actual reason for the `runtimeClass` parameter. I'm assuming this is used to create an array member? Well, for one thing, this precludes creating a queue of generic elements, because class instances are never generic. For another, it's just unnecessary: `ArrayList` is simply backed by a `Object[]`; casts to the element type are inserted by the compiler, at call sites. This simply isn't a particularly well-designed class. (And why not just use `ArrayDeque` anyway) – Andy Turner Jul 20 '19 at 19:30

1 Answers1

1

You don't need an instance of this queue at all.

Declare a type variable on the method signature:

public static <T> void adjacentPairs (ArrayQueue<T> arr)

Then just use a simple variable when you want to swap:

//swapping adjacentpairs
T a = arr.dequeue();
arr.enqueue(arr.dequeue());
arr.enqueue(a);
Andy Turner
  • 137,514
  • 11
  • 162
  • 243