Skip to content

Latest commit

 

History

History
74 lines (57 loc) · 1.57 KB

Ex_1_3_41.md

File metadata and controls

74 lines (57 loc) · 1.57 KB
title date draft tags categories
Algorithm4 Java Solution 1.3.41
2019-07-28 08:47:27 +0800
false
JAVA
TECH
archives

1.3.41

Problem:

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.

Solution:

code:

Ex_1_3_41.java

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;
    }
  }

Reference:

clone