1

元のキューをコピーしてキューの内容を出力してから、コピーを再度実行して、キュー内の要素の総数を出力しようとしています。元のキューで 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;

}
4

1 に答える 1

0

メソッド CopyQueue は単に間違っています。キューの内容をコピーする代わりに、エイリアシングを使用しています。

あなたがするとき:

public static LinkedUnbndQueue CopyQueue(LinkedUnbndQueue orig){
  LinkedUnbndQueue copy = orig;
  return copy;
}

同じ元のキューを指すポインターを返しています。キューをコピーする場合は、次のような新しい構造のすべての要素をコピーする必要があります。

public static LinkedUnbndQueue CopyQueue(LinkedUnbndQueue orig){
  LinkedUnbndQueue copy = new LinkedUnbndQueue();
  for(Object o : orig){
     copy.add(o);
  }
  return copy;
}
于 2014-01-14T14:25:17.420 に答える