深层复制并返回一个实例 Java

Deep copy and returning an instance Java

所以我正在做大学一年级的作业问题,我会诚实地说。我只想在你们中的一些人对我的问题进行投票之前把事情弄清楚。我不想要完整的代码,我只想在一些事情上得到一些帮助。

问题分为两部分。第一部分是编写一个 Nucleotide class 其构造函数具有两个属性。一个名为 base 的字符必须是 'a' 或 'c' 或 'g' 或 't' 否则它应该是 'n' 和一个布尔值 degenerate.

我这部分的代码在这里:

class Nucleotide {
    private char base;
    private boolean degenerate;

    public nucleotide(char base, boolean degenerate){
      if(base != ‘a’ || base != ‘c’ || base != ‘g’ || base != ’t’){
        this.base = ’n’;
      } else {
          this.base = base;
      }
      this.degenerate = degenerate;
    }
}

问题的下一部分说使用 Nucleotide 对象并创建一个新的 Bacteria class。一个细菌实例由一个基因组(一组核苷酸)和一个物种(一个字符串)组成。

您必须创建一个接受字符串和集合的构造函数,并使用它们来 初始化核苷酸的种类和集合。 我这部分的代码在这里:

class Bacteria {
  //private ArrayList<Nucleotide> genome;
  private String species;

  public Bacteria(String species, ArrayList<Nucleotide> genome) {
    genome = new ArrayList<Nucleotide>();
    this.species = species;
  }

My problem starts with the next step which asks us to write an instance method that performs deep copy and returns an instance of Bacteria.

public Bacteria binaryFission() {

如何在没有序列化和反射的情况下执行深拷贝。我对那些事情几乎一无所知。

我再次需要指导或关于如何完成 binaryFission() 方法的基本思路。 我已经完成了 SO 上的几个深层复制问题,但其中 none 与我的问题相关,所以我不认为我在问重复的问题。 我不过,我很乐意提供更多详细信息。

由于 Nucleotide 没有设置器,并且它的字段是原始的,它实际上是不可变的(无法更改,因此对 "reuse" 是安全的)。您最好将字段 final 正式设为不可变。

进行深拷贝所需要做的就是对 Nucleotide 列表进行浅拷贝,然后在新的 Bacteria 中使用它。你可以这样复制:

List<Nucleotide> copy = new ArrayList<>(genome);

您可以在 Bacteria 上创建一个简单的工厂方法,returns 是其自身的深层副本:

public Bacteria copy() {
   return new Bacteria(species, new ArrayList<>(genome));
}

这是手动完成的方法

public Bacteria binaryFission() {
    String speciesClone = this.species;
    ArrayList<Nucleotide> genomeClone = new ArrayList<Nucleotide>();
    //now iterate over the existing arraylist and clone each Nucleotide
    for(int index = 0; index < this.genome.size(); index++)
    {
        genomeClone.add(new Nucleotide(
                            genome.get(index).getBase(), //needs to be added to the Nucleotide class to retrieve the base variable
                            genome.get(index).getDegenerate() //needs to be added to be allowed to get its degenerate
                ));
    }

    return new Bacteria(speciesClone, genomeClone);
}

仅供参考 - 您需要为您的核苷酸添加吸气剂 class 私有变量才能使其正常工作,因为它们是私有的,没有它们细菌将无法访问它们的值。