求助啊--关于arraylist的
大家看啊,下面这段代码是没问题的import java.util.ArrayList;
import java.util.Random;
public class GA {
public int chromosomeLong;//染色体长度
public int initChromosomeNum;//初始染色体数目
public ArrayList<int[]> population = new ArrayList<int[]>();//保存当代染色体
public GA() {
}
public GA(int initChromosomeNum, int chromosomeLong,
double crossOverProbability, double mutationProbability) {
this.chromosomeLong = chromosomeLong;
this.crossOverProbability = crossOverProbability;
this.mutationProbability = mutationProbability;
this.initChromosomeNum = initChromosomeNum;
}
/**
* 随机产生第一代
*
* 初始群体个数 initChromosomeNum
*
*/
public void generateInitAllPopulation() {
if(population.size()!=0){
population.clear();
}
for (int i = 0; i < initChromosomeNum; i++) {
int[] chromosome = generateChromosome();
population.add(i, chromosome);
}
}
/**
* 随机产生单个染色体 染色体长度populationLong
*
*/
public int[] generateChromosome() {
int[] chromosome = new int[chromosomeLong];
for (int i = 0; i < chromosomeLong; i++) {
double random = Math.random();
if (random <= 0.5) {
chromosome = 1;
} else {
chromosome[i] = 0;
}
}
return chromosome;
}
然而当我想把population 改换成二维数组时却出了问题,看下面的代码
import java.util.ArrayList;
import java.util.Random;
public class GA {
public int chromosomeLong;//染色体长度
public int num;//卖家个数
public int initChromosomeNum;//初始染色体数目
[i]public ArrayList<int[][]> population = new ArrayList<int[][]>();//保存当代染色体
public GA() {
}
public GA(int num,int initChromosomeNum, int chromosomeLong,
double crossOverProbability, double mutationProbability) {
this.chromosomeLong = chromosomeLong;
this.crossOverProbability = crossOverProbability;
this.mutationProbability = mutationProbability;
this.num=num;
this.initChromosomeNum = initChromosomeNum;
}
/**
* 随机产生第一代
*
* 初始群体个数 initChromosomeNum
*
*/
public void generateInitAllPopulation() {
if(population.size()!=0){
population.clear();
}
for(int j=1;j<=num;j++){
for (int i = 1; i <= initChromosomeNum; i++) {
int[] chromosome = generateChromosome();
population[j].add(i, chromosome); //////这里出了错误???????????????
}
}
}
/**
* 随机产生单个染色体 染色体长度populationLong
*
*/
public int[] generateChromosome() {
int[] chromosome = new int[chromosomeLong];
for (int i = 0; i < chromosomeLong; i++) {
double random = Math.random();
if (random <= 0.5) {
chromosome[i] = 1;
} else {
chromosome[i] = 0;
}
}
return chromosome;
}
麻烦大家帮我改正啊,谢谢了!
搜索更多相关的解决方案:
arraylist
----------------解决方案--------------------------------------------------------