我正在尝试复制原始队列并打印出队列中的内容,然后再次运行副本并打印队列中的元素总数。当我在原始队列上运行CopyQueue方法并将其用作我的ShowQueue方法的输入时,它会更改原始队列。
public static void main(String[] args) {
LinkedUnbndQueue test = new LinkedUnbndQueue();
test.enqueue('a');
test.enqueue('b');
System.out.println( showQueue(CopyQueue(test)) );
System.out.println( Count(CopyQueue(test)) );
}
public static LinkedUnbndQueue CopyQueue(LinkedUnbndQueue orig){
LinkedUnbndQueue copy = orig;
return copy;
}
public static int Count(LinkedUnbndQueue orig){
int count = 0;
while(!orig.isEmpty() ){
orig.dequeue();
count = count + 1;
}
return count;
}
public static String showQueue(LinkedUnbndQueue orig){
String str = "";
while(!orig.isEmpty()){
str = str + orig.dequeue() + " ";
}
return str;
}
答案 0 :(得分:0)
您的方法CopyQueue完全错误。您正在使用别名而不是复制队列的内容。
当你这样做时:
public static LinkedUnbndQueue CopyQueue(LinkedUnbndQueue orig){
LinkedUnbndQueue copy = orig;
return copy;
}
您正在返回指向同一orig队列的指针。如果要复制队列,则需要复制新结构中的所有元素,如:
public static LinkedUnbndQueue CopyQueue(LinkedUnbndQueue orig){
LinkedUnbndQueue copy = new LinkedUnbndQueue();
for(Object o : orig){
copy.add(o);
}
return copy;
}