title | date | draft | tags | categories | |||
---|---|---|---|---|---|---|---|
Algorithm4 Java Solution 1.3.41 |
2019-07-28 08:47:27 +0800 |
false |
|
|
Copy a queue. Create a new constructor so that Queue<Item> r = new Queue<Item>(q);
makes r a reference to a new and independent copy of the queue q. You should be able to push and pop from either q or r without influencing the other. Hint : Delete all of the elements from q and add these elements to both q and r.
code:
To my best understanding, to copy a queue, we must also copy item.
Type <Item>
needs to implement Cloneable interface.
eg:
public _Queue (_Queue<Item> another){
if(!another.isEmpty()){
for(Item item : another){
// this.enqueue(item);
try{
this.enqueue((Item)item.getClass().getDeclaredMethod("clone", null).invoke(item));
}catch (Exception e){
e.printStackTrace();
}finally {
this.enqueue(item);
}
}
}
}
public static class Student implements Cloneable{
String name;
public Student(String name){
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
Student other = new Student(this.name);
return other;
}
}