을 감상 할 수있다 : 당신의 사양에 따라 (나는 [] 네 개의 숫자에 문자하는 유전자가), 당신이 char
배열과 필요를 클래스의 속성. 또한이 클래스는 복제 가능해야하며이 클래스는 Cloneable
인터페이스를 구현해야합니다. 즉, Gene
클래스는 Cloneable
인터페이스를 구현하고 (클래스 정의에 implements Cloneable
을 작성하기 만하면 됨) 선언해야하며 clone
을 구현해야합니다. 메서드를 호출해야합니다 (이 메서드에서는 개체 필드의 전체 복사본을 만들고 복제 된 개체를 반환해야합니다. 자세한 내용은 아래 코드를 참조하십시오). (배열 복사에 대한 자세한 내용은 here를 참조하시기 바랍니다) 나는 방법 Arrays
클래스의 copyOf
을 사용하는 배열을 복사하는
import java.util.Arrays;
/*
* Definition of the class that also includes the declaration
* of the implementation of the Cloneable interface.
*/
public class Gene implements Cloneable {
/*
* The length of a gene.
* It is defined as constant (final) in order to use the same value
* in the whole class, where and when necessary.
*/
private static final int GENE_LENGTH = 4;
/*
* In biology a gene it corresponds to a sequence of nucleic acids,
* so I thought of naming m_sequence this field.
*/
private char m_sequence[];
/*
* This constructor allows you to instantiate a new object from a char array.
*/
public Gene(char sequence[]) {
// The field m_sequence is initialized with a copy
// of the array specified in the constructor.
m_sequence = Arrays.copyOf(sequence, GENE_LENGTH);
}
/*
* Simple getter method.
* Since m_sequence is private, you need a method like this
* in order to access elements of the array.
*/
public char getUnit(int index) {
return m_sequence[index];
}
/*
* Simple setter method.
* Since m_sequence is private, you need a method like this
* in order to set the elements of the array.
*/
public void setUnit(int index, char unit) {
m_sequence[index] = unit;
}
/*
* The Cloneable declaration requires that this class has clone method.
* This method should return an Gene object within an Object.
*/
protected Object clone() throws CloneNotSupportedException {
// First, we invoke the clone method of the superclass
Gene clone = (Gene)(super.clone());
// Then, make the deep copy of the object.
// In this case the only field present in the Gene object is an array,
// then you must make a deep copy of this array: in order to make a deep
// copy of the array, you should use the Arrays.copyOf method.
clone.m_sequence = Arrays.copyOf(m_sequence, GENE_LENGTH);
return clone;
}
/*
* Get a representation of this object as a String.
* Just a method for simple testing.
*/
@Override
public String toString() {
return Arrays.toString(m_sequence);
}
}
참고.
간단한 테스트
는
Gene
객체의 딥 카피의 기능을 확인합니다 :
public static void main(String args[]) throws CloneNotSupportedException {
Gene g1 = new Gene(new char[]{'a', 'b', 'c', 'd'});
Gene g2 = (Gene)(g1.clone());
// now Let's modify g1
g1.setUnit(0, 'e');
g1.setUnit(1, 'f');
g1.setUnit(2, 'g');
g1.setUnit(3, 'h');
System.out.println("g1: " + g1);
System.out.println("g2: " + g2); // g2 has not changed
}
을 따라서, 다음과 같이 당신이 당신의 createChild
방법을 변경해야합니다.
public class Chromosome {
private static final int CHROMOSOME_LENGTH = 10;
/* Array of Gene object. */
private Gene genes[];
/* Default constructor. */
public Chromosome() {
// Simply allocates an array of 10 elements.
genes = new Gene[CHROMOSOME_LENGTH];
}
/*
* Simple getter method.
* Since m_Genes is private, you need a method like this
* in order to access elements of the array.
*/
public Gene getGene(int index) {
return genes[index];
}
/*
* Simple setter method.
* Since m_Genes is private, you need a method like this
* in order to set the elements of the array.
*/
public void setGene(int index, Gene gene) {
genes[index] = gene;
}
/* The method which make the cross-over. */
public Chromosome createChild(Chromosome parentA, Chromosome parentB) throws CloneNotSupportedException {
Chromosome child = new Chromosome();
// make the cross-over
for (int i=0;i<10; i++)
{
if (i<5)
{
// you need to call the clone() method
child.genes[i] = (Gene)(parentA.genes[i].clone());
}
else
{
// you need to call the clone() method
child.genes[i] = (Gene)(parentB.genes[i].clone());
}
}
return child;
}
}
는'가변 genes' 있습니까? 다시 할당하지 않고 값을 수정할 수있는 연산이 있습니까? –
안녕하세요, 보리스, 아이 염색체에 영향을 줄 뮤 테이터 클래스가 있습니다. 그래서 부모와 자식을위한 별도의 배열이 필요합니다. –
예, 이미 별개의 배열입니다. 단지 그들이 동일한'.gene' 객체를 공유한다는 것입니다. 나는 아직도 이것이 어떤 문제를 일으키는 지 확신하지 못하고있다. 왜냐하면 나는'유전자 '의 가치를 변화시킬 작전을 생각할 수 없기 때문이다. 이 객체의 유형을 공유해 주시겠습니까? 그리고 당신이 선언 한 코드를 질문에 포함 시키시겠습니까? –