实例化新的 ArrayDeque 以保持通用
Instatiate new ArrayQueue to remain Generic
我需要创建第二个与传入类型相同的 ArrayQueue,以便我可以在队列中添加项目。我无法实例化第二个 ArrayQueue,除非我将其设为特定的 class,这违背了通用的目的,并且当测试从整数、字符、对象或布尔值切换时测试失败。
测试用例传入一个ArrayQueue进行操作,但代码需要创建第二个与传入相同类型的ArrayQueue。我尝试使用as类型但它没有编译。
示例
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());
}
}
}
您根本不需要此队列的实例。
在方法签名上声明类型变量:
public static <T> void adjacentPairs (ArrayQueue<T> arr)
然后当你想交换的时候只用一个简单的变量:
//swapping adjacentpairs
T a = arr.dequeue();
arr.enqueue(arr.dequeue());
arr.enqueue(a);
我需要创建第二个与传入类型相同的 ArrayQueue,以便我可以在队列中添加项目。我无法实例化第二个 ArrayQueue,除非我将其设为特定的 class,这违背了通用的目的,并且当测试从整数、字符、对象或布尔值切换时测试失败。
测试用例传入一个ArrayQueue进行操作,但代码需要创建第二个与传入相同类型的ArrayQueue。我尝试使用as类型但它没有编译。
示例
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());
}
}
}
您根本不需要此队列的实例。
在方法签名上声明类型变量:
public static <T> void adjacentPairs (ArrayQueue<T> arr)
然后当你想交换的时候只用一个简单的变量:
//swapping adjacentpairs
T a = arr.dequeue();
arr.enqueue(arr.dequeue());
arr.enqueue(a);