是不是数组中的每个类元素都共用一些相同的存储空间?我的程序是出现了这样的问题,我现在想使每个类元素有单独的存储空间,应该怎么办?

解决方案 »

  1.   

    不可能,类对象是不可以拷贝的。想想看,如果同一个类对象在内存中有几个,那使用new的时候依据哪个来实例化????楼主不妨说说看你要解决的问题是什么,现在来看,你的思路可能已经错了。
      

  2.   

    晕啊~~~~~~~ 误会你的意思了,不好意思~~~~~~~~数组中存储的不是对象本身,而是对象的引用,你通过引用去修改一个对象,那其它的引用如果也指向同一个对象的话,当然是一起变啦。为数组元素赋值时,应该每个都用new XXX()来创建新的对象,这样他们就是各不相同的对象了。
      

  3.   

    Dan1980()  
    new XXX()早就用了,不用肯定不行.
    但问题不在这里,是在程序执行过程中,数组中的元素(类的实例)中的变量值的变化问题,数组中元素有很多个,都是我自定义的类的实例,每个类实例里也有变量,相当于C里面的struct数组的用法,就好像数组中又有数组,里面的变量值的变化出现上面我说的情况,而我在vC++6.0中去实现的话一切正常,在jbuilder2006中做时却出现了莫名其妙的结果,我不知道在javak中是不是多个类实例的变量共享同一个存储空间????????????
      

  4.   

    public class TestObject 
    {
    public int    iInt   = 0;
    public String strStr = new String();

    TestObject(String strTest, int iTest)
    {
    this.strStr = strTest;
    this.iInt   = iTest;
    }

    public String toString()
    {
    return "this.strStr = " + this.strStr + "\nthis.iInt   = " + this.iInt;
    }
    }
    public class TestArray 
    {
    public static void main(String[] arg)
    {
    List a1 = new ArrayList();
    TestObject to = null;
    for(int i=0; i<10; i++)
    {
    to = new TestObject(String.valueOf(i), i);
    a1.add(to);
    }

    System.out.println("============= test1 begin =============");
    for(int i=0; i<a1.size(); i++)
    {
    System.out.println(i + " = " + a1.get(i).toString());
    }
    System.out.println("=============  test1 end  =============");
    }
    }
    我觉可能是你粗心的问题;或者你使用了static关键字;
      

  5.   

    vc的代码拿到JAVA中来编译,狂汗啊~~~~~~~~
    还是楼上说的,上代码~~
      

  6.   

    代码比较长.
    package traffic;import java.io.IOException;
    import java.io.File;
    import java.io.FileReader;
    import java.io.*;public class GeneticAlgorithm {
        /*
             其中, k=0.314159, t是时间(单位为秒)
             路口各个方向各个车道在允许放行条件下最大放行车辆数为80辆/分, 固定周期T为120秒
             种群数取为150, 染色体长度n 取为24, 总迭代代数取为50 东、南、西、北的左、
             中、右各车道的车流到达率分别假定为:
         */    /*
             A. M:群体大小。一般取为20~100;
             B. T:遗传运算终止进化代数。一般取为100~500;
             C. Pc:交叉概率。一般取为0.4~0.99;
             D. Pm:变异概率。一般取为0.0001~0.1。
         */
        /* Change any of these parameters to match your needs */    static int POPSIZE = 4; /* population size */
        static int MAXGENS = 4; /* max. number of generations */
        static int NVARS = 3; /* no. of problem variables */
        static float PXOVER = 0.8f; /* probability of crossover */
        static float PMUTATION = 0.8f; /* probability of mutation */    int E = 6; //考虑路口行人过马路时的安全需要, 每相位最短绿灯时间不得小于某值e
        int T = 120; //固定周期T秒
        int generation; /* current generation no. */
        int cur_best; /* best individual */
        //FILE * galog; /* an output file */    BufferedReader infile;
        FileReader in;
        BufferedWriter outfile;
        FileWriter out;    Genotype population[];
        Genotype newpopulation[];
        //四相位变化控制的单交叉路口, 不同的相位、不同的车道的车辆放行状态可用一个系数矩阵pe表示,
        int p[][][] = { { {0, 1, 1}, {0, 0, 0}, {0, 1, 1}, {0, 0, 0}
        }, { {1, 0, 0}, {0, 0, 0}, {1, 0, 0}, {0, 0, 0}
        }, { {0, 0, 0}, {0, 1, 1}, {0, 0, 0}, {0, 1, 1}
        }, { {0, 0, 0}, {1, 0, 0}, {0, 0, 0}, {1, 0, 0}
        }
        };
    //车辆到达率
        double a[][][] = { { {10, 1, 1}, {10, 2, 4}, {1, 2.3, 1}, {3, 5, 1}
        }, { {1, 3, 0.8}, {2, 3, 1.5}, {1, 1, 2}, {2, 0.7, 4}
        }, { {2.5, 1.2, 3.4}, {10, 1, 1}, {1, 0.8, 13}, {1.9, 1, 1}
        }, { {0.4, 3, 2.3}, {1, 2.1, 4}, {3.2, 1, 0.5}, {1, 1.4, 1.6}
        }
        };
    //车辆离开路口率
        double u[][][] = { { {2, 1, 1}, {3, 2, 4}, {1, 2.3, 1}, {3, 2, 1}
        }, { {1, 3, 0.8}, {2, 3, 1.5}, {1, 1, 0.9}, {2, 0.7, 4}
        }, { {0.7, 1.2, 3.4}, {0.5, 1, 1}, {1, 0.8, 0.9}, {1.9, 1, 1}
        }, { {0.4, 3, 2.3}, {1, 2.1, 4}, {0.4, 1, 0.3}, {1, 1.4, 0.8}
        }
        };
    //各路口滞留车辆数
        double s[][][] = { { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}
        }, { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}
        }, { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}
        }, { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}
        }, { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}
        }
        };    GeneticAlgorithm() {
            //以下这两句话只是构造了数组对象,但数组里的元素都还是空的
            population = new Genotype[POPSIZE+1]; /* population */
            newpopulation = new Genotype[POPSIZE+1]; /* new population; */
            for (int i = 0; i <= POPSIZE; i++) {
                population[i] = new Genotype();
                newpopulation[i] = new Genotype();
            }
        }    class Genotype /* genotype (GT), a member of the population */
                {
            double gene[];
            double fitness;
            double upper[];
            double lower[];
            double cfitness;
            double rfitness;
            Genotype() {
                gene = new double[NVARS]; /* a string of variables */
                fitness = 0; /* GT's fitness */
                upper = new double[NVARS]; /* GT's variables upper bound */
                lower = new double[NVARS]; /* GT's variables lower bound */
                rfitness = 0; /* relative fitness */
                cfitness = 0; /* cumulative fitness */
            }
        }    void initialize() {
            String str;
            String parts[];
            try {
                in = new FileReader("gadata.txt");
                infile = new BufferedReader(in);
                int i, j;
                double lbound, ubound;
                while ((str = infile.readLine()) != null) {
                    parts = str.split(" ");
                    for (i = 0; i < NVARS; i++) {
                        lbound = Double.parseDouble(parts[0]);
                        ubound = Double.parseDouble(parts[1]);                    for (j = 0; j < POPSIZE; j++) {
                            population[j].fitness = 0;
                            population[j].rfitness = 0;
                            population[j].cfitness = 0;
                            population[j].lower[i] = lbound;
                            population[j].upper[i] = ubound;
                            population[j].gene[i] = randval(population[j].lower[i],
                                    population[j].upper[i]);
                            newpopulation[j].fitness = 0;
                            newpopulation[j].rfitness = 0;
                            newpopulation[j].cfitness = 0;
                            newpopulation[j].lower[i] = lbound;
                            newpopulation[j].upper[i] = ubound;
                            newpopulation[j].gene[i] = randval(newpopulation[j].lower[i],
                                    newpopulation[j].upper[i]);
                        }
                    }
                }
                infile.close();
            }        catch (IOException e1) {
                System.out.println("Can not open input file!");
                System.exit(0);
            }
        }    /***********************************************************/
        /* Random value generator: Generates a value within bounds */
        /***********************************************************/    double randval(double low, double high) {
            double val;
            val = (double) java.lang.Math.random() * (high - low) + low;
            return (val);
        }    /*************************************************************/
        /* Evaluation function: This takes a user defined function.  */
        /* Each time this is changed, the code has to be recompiled. */
        /* The current function is:  x[1]^2-x[1]*x[2]+x[3]           */
        /*************************************************************/
        void display() {
            int i, j;
            for (j = 0; j <= POPSIZE; j++) {
                for (i = 0; i < NVARS; i++) {
                    System.out.print(population[j].gene[i] + "\t");
                }
                System.out.printf("             " + population[j].fitness);
                System.out.print("\n");
            }
            System.out.print("\n");
        }
      

  7.   

    void evaluate() {
            int mem;
            int i, j, k;
            double t[] = new double[NVARS + 1];        double sum = 0;
            double min = 0;        for (mem = 0; mem < POPSIZE; mem++) {
                sum = 0;
                min = 0;
                for (i = 0; i < NVARS; i++) {
                    t[i] = population[mem].gene[i];
                    sum += t[i];
                }
                t[3] = T - sum;
                if (t[3] < E || t[3] > (T - 3 * E)) {
                    population[mem].fitness = 0;
                    continue;
                }
                for (i = 1; i < 5; i++) {
                    for (j = 0; j < 4; j++) {
                        for (k = 0; k < 3; k++) {
                            if (s[i - 1][j][k] + a[i - 1][j][k] * t[i - 1] >=
                                p[i - 1][j][k] * u[i - 1][j][k] * t[i - 1]) {
                                s[i][j][k] = s[i - 1][j][k] + a[i - 1][j][k] * t[i -
                                             1] - p[i - 1][j][k] * u[i -
                                             1][j][k] * t[i - 1];
                            } else {
                                s[i][j][k] = 0;
                            }
                        }
                    }
                }
                for (j = 0; j < 4; j++) {
                    for (k = 0; k < 3; k++) {
                        //s[0][j][k]=s[4][j][k];
                        min += s[4][j][k];
                    }
                }
                population[mem].fitness = 10000 - min;
            }
        }    /***************************************************************/
        /* Keep_the_best function: This function keeps track of the    */
        /* best member of the population. Note that the last entry in  */
        /* the array Population holds a copy of the best individual    */
        /***************************************************************/    void keep_the_best() {
            int mem;
            int i;
            cur_best = 0; /* stores the index of the best individual */        for (mem = 0; mem < POPSIZE; mem++) {
                if (population[mem].fitness > population[POPSIZE].fitness) {
                    cur_best = mem;
                    population[POPSIZE].fitness = population[mem].fitness;
                }
            }
            /* once the best member in the population is found, copy the genes */
            for (i = 0; i < NVARS; i++) {
                population[POPSIZE].gene[i] = population[cur_best].gene[i];
            }    }    /****************************************************************/
        /* Elitist function: The best member of the previous generation */
        /* is stored as the last in the array. If the best member of    */
        /* the current generation is worse then the best member of the  */
        /* previous generation, the latter one would replace the worst  */
        /* member of the current population                             */
        /****************************************************************/    void elitist() {
            int i;
            double best, worst; /* best and worst fitness values */
            int best_mem = 0;
            int worst_mem = 0;
                                       /* indexes of the best and worst member */        best = population[0].fitness;
            worst = population[0].fitness;
            for (i = 0; i < POPSIZE - 1; ++i) {
                if (population[i].fitness > population[i + 1].fitness) {
                    if (population[i].fitness >= best) {
                        best = population[i].fitness;
                        best_mem = i;
                    }
                    if (population[i + 1].fitness <= worst) {
                        worst = population[i + 1].fitness;
                        worst_mem = i + 1;
                    }
                } else {
                    if (population[i].fitness <= worst) {
                        worst = population[i].fitness;
                        worst_mem = i;
                    }
                    if (population[i + 1].fitness >= best) {
                        best = population[i + 1].fitness;
                        best_mem = i + 1;
                    }
                }
            }
            /* if best individual from the new population is better than */
            /* the best individual from the previous population, then    */
            /* copy the best from the new population; else replace the   */
            /* worst individual from the current population with the     */
            /* best one from the previous generation                     */
            System.out.println("刚完成精英主义前");
            display();
    System.out.print("\n\n"+best_mem+"\t"+worst_mem+"\t"+best+"\t"+worst+"\n\n");
            if (best >= population[POPSIZE].fitness) {
                for (i = 0; i < NVARS; i++) {
                    population[POPSIZE].gene[i] = population[best_mem].gene[i];
                }
                population[POPSIZE].fitness = population[best_mem].fitness;
            }
            else {
                for (i = 0; i < NVARS; i++) {
                    population[worst_mem].gene[i] = population[POPSIZE].gene[i];
                }
                {System.out.print("\n\n"+best_mem+"\t"+worst_mem+"\t"+best+"\t"+worst+"\n\n");
                population[worst_mem].fitness = population[POPSIZE].fitness;}
            }
            System.out.println("刚完成精英主义后");
            display();
        }    /**************************************************************/
        /* Selection function: Standard proportional selection for    */
        /* maximization problems incorporating elitist model - makes  */
        /* sure that the best member survives                         */
        /**************************************************************/    void select() {
            int mem, i, j;
            double sum = 0;
            double p;        /* find total fitness of the population */
            for (mem = 0; mem < POPSIZE; mem++) {
                sum += population[mem].fitness;
            }        /* calculate relative fitness */
            for (mem = 0; mem < POPSIZE; mem++) {
                population[mem].rfitness = population[mem].fitness / sum;
            }
            population[0].cfitness = population[0].rfitness;
            /* calculate cumulative fitness */
            for (mem = 1; mem < POPSIZE; mem++) {
                population[mem].cfitness = population[mem - 1].cfitness +
                                           population[mem].rfitness;
            }
            /* finally select survivors using cumulative fitness. */
            for (i = 0; i < POPSIZE; i++) {
                p = java.lang.Math.random();
                if (p < population[0].cfitness) {
                    newpopulation[i] = population[0];
                } else {
                    for (j = 0; j < POPSIZE - 1; j++) {
                        if (p >= population[j].cfitness &&
                            p < population[j + 1].cfitness) {
                            newpopulation[i] = population[j + 1];
                            break;
                        }
                    }
                }
            }
            /* once a new population is created, copy it back */        for (i = 0; i < POPSIZE; i++) {
                population[i] = newpopulation[i];
            }
        }
      

  8.   

    void crossover() {
            int mem, one = 0;
            int first = 0; /* count of the number of members chosen */
            double x;        for (mem = 0; mem < POPSIZE; mem++) {
                x = java.lang.Math.random();
                if (x < PXOVER) {
                    ++first;
                    if (first % 2 == 0) {
                        Xover(one, mem);
                    } else {
                        one = mem;
                    }
                }
            }
        }    /**************************************************************/
        /* Crossover: performs crossover of the two selected parents. */
        /**************************************************************/    void Xover(int one, int two) {
            int i;
            int point; /* crossover point */
            double temp;        /* select crossover point */
            if (NVARS > 1) {
                if (NVARS == 2) {
                    point = 1;
                } else {
                    point = ((int) (java.lang.Math.random() * 100) % (NVARS - 1)) +
                            1;
                }
                for (i = 0; i < point; i++) {
                    temp = 0;
                    temp = population[one].gene[i];
                    population[one].gene[i] = population[two].gene[i];
                    population[two].gene[i] = temp;
                }
            }
        }    /*************************************************************/
        /* Swap: A swap procedure that helps in swapping 2 variables */
        /*************************************************************/    /*void swap(double x, double y) {
            double temp;        temp = x;
            x = y;
            y = temp;         }*/    /**************************************************************/
        /* Mutation: Random uniform mutation. A variable selected for */
        /* mutation is replaced by a random value between lower and   */
        /* upper bounds of this variable                              */
        /**************************************************************/    void mutate() {
            int i, j;
            double lbound, hbound;
            double x;        for (i = 0; i < 2; i++) {
                for (j = 0; j < NVARS; j++) {
                    x = java.lang.Math.random();
                    if (x < PMUTATION) {
                        /* find the bounds on the variable to be mutated */
                        lbound = population[i].lower[j];
                        hbound = population[i].upper[j];
                        population[i].gene[j] = randval(lbound, hbound);
                        System.out.print(i+"\t"+j+"\t"+population[i].gene[j]+"\n");
                    }
                }
            }System.out.print("\n");
        }    /***************************************************************/
        /* Report function: Reports progress of the simulation. Data   */
        /* dumped into the  output file are separated by commas        */
        /***************************************************************/    void report() {
            int i;
            double best_val; /* best population fitness */
            double avg; /* avg population fitness */
            double stddev; /* std. deviation of population fitness */
            double sum_square; /* sum of square for std. calc */
            double square_sum; /* square of sum for std. calc */
            double sum; /* total population fitness */        sum = 0.0;
            sum_square = 0.0;        for (i = 0; i < POPSIZE; i++) {
                sum += population[i].fitness;
                sum_square += population[i].fitness * population[i].fitness;
            }        avg = sum / (double) POPSIZE;
            square_sum = avg * avg * POPSIZE;
            stddev = java.lang.Math.sqrt((sum_square - square_sum) / (POPSIZE - 1));        best_val = population[POPSIZE].fitness;
            try {
                outfile.write("\r\n" + generation + "       ");
                outfile.write(best_val + "      "); //"\n%5d,      %6.3f, %6.3f, %6.3f \n\n", generation,
                outfile.write(avg + "      "); // best_val, avg, stddev);
                outfile.write(stddev + "      ");
            } catch (IOException e1) {
            }
        }    /**************************************************************/
        /* Main function: Each generation involves selecting the best */
        /* members, performing crossover & mutation and then          */
        /* evaluating the resulting population, until the terminating */
        /* condition is satisfied                                     */
        /**************************************************************/    public void Entrance() {
            int i;
            double sum = 0;
            try {
                out = new FileWriter("galog.txt");
                outfile = new BufferedWriter(out);
                outfile.write("\r\ngeneration  best  average  standard\r\n");
                outfile.write("number      value fitness  deviation \r\n");
            }        catch (IOException e1) {
                return;
            }
            generation = 0;
            initialize();
            System.out.println("初始化后");
            display();
            evaluate();
            System.out.println("计算适应值后");
            display();
            keep_the_best();
            System.out.println("保持最好值后");
            display();
            while (generation < MAXGENS) {
                generation++;
                select();
                System.out.println("选择后");
                display();
                crossover();
                System.out.println("交叉后");
                display();
                mutate();
                System.out.println("变异后");
                display();
                evaluate();
                System.out.println("计算适应值后");
                display();
                elitist();
                System.out.println("精英主义后");
                display();
                report();
            }
            try {
                outfile.write("\r\n\r\n Simulation completed\r\n");
                outfile.write("\r\n Best member: \r\n");            for (i = 0; i < NVARS; i++) {
                    outfile.write("\r\n var(" + i + ") = " +
                                  (int) population[POPSIZE].gene[i]);
                    sum += (int) population[POPSIZE].gene[i];
                }
                outfile.write("\r\n var(" + i + ") = " + (T - (int) sum));            outfile.write("\r\n\r\n Best fitness =" +
                              population[POPSIZE].fitness);
                outfile.close();
            } catch (IOException e1) {        }
            System.out.println("Success\r\n");
        }    public static void main(String[] args) {
            GeneticAlgorithm a = new GeneticAlgorithm();
            a.Entrance();
        }
    }
      

  9.   

    因为不能连发三个回复,所以还要加上下面的.
     void crossover() {
            int mem, one = 0;
            int first = 0; /* count of the number of members chosen */
            double x;        for (mem = 0; mem < POPSIZE; mem++) {
                x = java.lang.Math.random();
                if (x < PXOVER) {
                    ++first;
                    if (first % 2 == 0) {
                        Xover(one, mem);
                    } else {
                        one = mem;
                    }
                }
            }
        }    /**************************************************************/
        /* Crossover: performs crossover of the two selected parents. */
        /**************************************************************/    void Xover(int one, int two) {
            int i;
            int point; /* crossover point */
            double temp;        /* select crossover point */
            if (NVARS > 1) {
                if (NVARS == 2) {
                    point = 1;
                } else {
                    point = ((int) (java.lang.Math.random() * 100) % (NVARS - 1)) +
                            1;
                }
                for (i = 0; i < point; i++) {
                    temp = 0;
                    temp = population[one].gene[i];
                    population[one].gene[i] = population[two].gene[i];
                    population[two].gene[i] = temp;
                }
            }
        }    /*************************************************************/
        /* Swap: A swap procedure that helps in swapping 2 variables */
        /*************************************************************/    /*void swap(double x, double y) {
            double temp;        temp = x;
            x = y;
            y = temp;         }*/    /**************************************************************/
        /* Mutation: Random uniform mutation. A variable selected for */
        /* mutation is replaced by a random value between lower and   */
        /* upper bounds of this variable                              */
        /**************************************************************/    void mutate() {
            int i, j;
            double lbound, hbound;
            double x;        for (i = 0; i < 2; i++) {
                for (j = 0; j < NVARS; j++) {
                    x = java.lang.Math.random();
                    if (x < PMUTATION) {
                        /* find the bounds on the variable to be mutated */
                        lbound = population[i].lower[j];
                        hbound = population[i].upper[j];
                        population[i].gene[j] = randval(lbound, hbound);
                        System.out.print(i+"\t"+j+"\t"+population[i].gene[j]+"\n");
                    }
                }
            }System.out.print("\n");
        }    /***************************************************************/
        /* Report function: Reports progress of the simulation. Data   */
        /* dumped into the  output file are separated by commas        */
        /***************************************************************/    void report() {
            int i;
            double best_val; /* best population fitness */
            double avg; /* avg population fitness */
            double stddev; /* std. deviation of population fitness */
            double sum_square; /* sum of square for std. calc */
            double square_sum; /* square of sum for std. calc */
            double sum; /* total population fitness */        sum = 0.0;
            sum_square = 0.0;        for (i = 0; i < POPSIZE; i++) {
                sum += population[i].fitness;
                sum_square += population[i].fitness * population[i].fitness;
            }        avg = sum / (double) POPSIZE;
            square_sum = avg * avg * POPSIZE;
            stddev = java.lang.Math.sqrt((sum_square - square_sum) / (POPSIZE - 1));        best_val = population[POPSIZE].fitness;
            try {
                outfile.write("\r\n" + generation + "       ");
                outfile.write(best_val + "      "); //"\n%5d,      %6.3f, %6.3f, %6.3f \n\n", generation,
                outfile.write(avg + "      "); // best_val, avg, stddev);
                outfile.write(stddev + "      ");
            } catch (IOException e1) {
            }
        }    /**************************************************************/
        /* Main function: Each generation involves selecting the best */
        /* members, performing crossover & mutation and then          */
        /* evaluating the resulting population, until the terminating */
        /* condition is satisfied                                     */
        /**************************************************************/    public void Entrance() {
            int i;
            double sum = 0;
            try {
                out = new FileWriter("galog.txt");
                outfile = new BufferedWriter(out);
                outfile.write("\r\ngeneration  best  average  standard\r\n");
                outfile.write("number      value fitness  deviation \r\n");
            }        catch (IOException e1) {
                return;
            }
            generation = 0;
            initialize();
            System.out.println("初始化后");
            display();
            evaluate();
            System.out.println("计算适应值后");
            display();
            keep_the_best();
            System.out.println("保持最好值后");
            display();
            while (generation < MAXGENS) {
                generation++;
                select();
                System.out.println("选择后");
                display();
                crossover();
                System.out.println("交叉后");
                display();
                mutate();
                System.out.println("变异后");
                display();
                evaluate();
                System.out.println("计算适应值后");
                display();
                elitist();
                System.out.println("精英主义后");
                display();
                report();
            }
            try {
                outfile.write("\r\n\r\n Simulation completed\r\n");
                outfile.write("\r\n Best member: \r\n");            for (i = 0; i < NVARS; i++) {
                    outfile.write("\r\n var(" + i + ") = " +
                                  (int) population[POPSIZE].gene[i]);
                    sum += (int) population[POPSIZE].gene[i];
                }
                outfile.write("\r\n var(" + i + ") = " + (T - (int) sum));            outfile.write("\r\n\r\n Best fitness =" +
                              population[POPSIZE].fitness);
                outfile.close();
            } catch (IOException e1) {        }
            System.out.println("Success\r\n");
        }    public static void main(String[] args) {
            GeneticAlgorithm a = new GeneticAlgorithm();
            a.Entrance();
        }
    }
      

  10.   

    我的一个执行结果:
    交叉后
    28.24858540511777 55.636895683556034 20.306689405679407              6875.694234472563
    28.24858540511777 55.636895683556034 20.306689405679407              6875.694234472563
    28.24858540511777 55.636895683556034 20.306689405679407              6875.694234472563
    28.24858540511777 55.636895683556034 20.306689405679407              6875.694234472563
    28.24858540511777 55.636895683556034 20.306689405679407              6875.694234472563应该变的是下面三个值,但整个数组的值都变成一样的了,只有最后一条没变.
    在代码中很明显我在mutate()函数中只用了这条语句population[i].gene[j] = randval(lbound, hbound);而且我也调试过,在这条语句处我设了一断点,当我执行完这条语句后,突然
    population[其它].gene[j]就是其它不是i但先前的值与population[i].gene[j]相同的全变成randval(lbound, hbound)了.
    i        j         值
    0 0 95.10484999001903
    0 1 59.53621614400595
    0 2 48.28104161723166变异后
    95.10484999001903 59.53621614400595 48.28104161723166              6875.694234472563
    95.10484999001903 59.53621614400595 48.28104161723166              6875.694234472563
    95.10484999001903 59.53621614400595 48.28104161723166              6875.694234472563
    95.10484999001903 59.53621614400595 48.28104161723166              6875.694234472563
    28.24858540511777 55.636895683556034 20.306689405679407              6875.694234472563
      

  11.   

    据我所知,创建了一个数组后,还要为其中对里面的每个元素进行创建.MyClass[] array=new MyClass[10];
    for(int i=0;i<10;i++)array[i]=new MyClass();
      

  12.   

    楼上的,我这个工作已做了.问题不在此啊,
    问题是这些元素出现存储空间共享,我不知道是不是?如果这样的话,那java也不科学了!!!!!!!
    程序实在是找不出问题.程序有点长,但不难懂,我都等了好久了,都没人来说两句,郁闷....
    高人指点一下啊.
      

  13.   

    kao gadata.txt里是什么啊?
    想帮你调试都没办法
      

  14.   

    哦,楼上的,对不起了,忘记了
    gadata.txt
    6 102
    6 102
    6 102
      

  15.   

    在select()里
    /* finally select survivors using cumulative fitness. */
            for (i = 0; i < POPSIZE; i++) {
                p = java.lang.Math.random();
                System.out.println("p == "+p+" ------- cfitness == "+population[0].cfitness);//这是我加的
                if (p < population[0].cfitness) { 
                    newpopulation[i] = population[0];//这里,导致后面的值变成相同
                } else {
                    for (j = 0; j < POPSIZE - 1; j++) {
                        if (p >= population[j].cfitness &&
                            p < population[j + 1].cfitness) {
                            newpopulation[i] = population[j + 1];
                            break;
                        }
                    }
                }
            }
      

  16.   

    你的值在select()之后就已经变了
      

  17.   

    wolf863292() ,非常感谢你来给我找错.但是select()是要它这样变化的..
    因为要选出最优化的结果.所以那些不符合要求当然不要了.你看没有,程序输出中的每一行的最后一个就是适应值,越大就表时它越优..所以每次选的话肯定不能选这个值为0的,只能在不为0的当中去选.程序要实现的功能是为交通灯优化配时.也就是说根据目前各道上的车流情况,动态地为路口的交通灯时间进行优化,从而使各条道上的滞留车辆总数最少.用的是遗传算法来给它优化配时,就好像一代一代地进化,逐步选出最优.问题就是上面所说的,变异那个函数(void mutate())不起作用了,我硬是调试了好久,我在
    population[i].gene[j] = randval(lbound, hbound);这句设了断点,但每次执行完这句后,整个population数组都改变了,并不像我想像的那样只改变其中某个值.唉,还请您重点帮我看看这块子,控制台有很多输出信息,都是我设置的,我为了对照,把变异前的population中gene的值和其变异后的值都输出来了.你帮我查查,我实在是受不了了!
      

  18.   

    lz,我暂时没时间细看,抱歉.
    但是在select()中,加上System.out.println("p == "+p+" ------- cfitness == "+population[0].cfitness);
    你自己看吧,不知哪次循环是将cfitness赋值1.0,而random()一定<0,
    你在
     for (i = 0; i < POPSIZE; i++) {
                p = java.lang.Math.random();
                if (p < population[0].cfitness) { 
    ...
    时则从0到POPSIZE都赋予了相同的值.
    大概是for (i = 0; i < POPSIZE; i++) 有问题吧?
      

  19.   

    另,在while()的开头加入{
    System.out.println("-----------------------------------------------");
    System.out.println("while times = "+generation++);
    display();
    System.out.println("-----------------------------------------------");
    ...
    ...
    ...
    }
    可能对你有点帮助.
    你可以看到,每次while,值全都变成相同的了.
      

  20.   

    不是排序,是一个遗传算法.也就是找符合某个约束条件的最优解.本程序就是交通灯一个周期的时间固定的情况下,我设的是120,在galog.txt最后出现的四个变量值就相当于最优值.而且四个变量值都在6 --102之间.
    Best member: 
     var(0) = xx
     var(1) = xx
     var(2) = xx
     var(3) = xx
    但结果出不来.好像没有进化一样.
      

  21.   

    to dash_running() ( ) 信誉:100    Blog 
    只是一部分吧.就是这结果有问题,你对照一下,帮我找找!
      

  22.   

    我找了好多次,都是在select后,变成相同值的.
    不行了,不知道应该输出什么,怎么判断啊?
    我始终觉得不是变异那个函数(void mutate())的问题.下班了,不好意思,886.
      

  23.   

    Class[] cls = new Class[3];
    cls[0] = Class.class;
    cls[1] = Object.class;
    cls[2] = String.class;
      

  24.   

    怎么这么多专家们就没有一个有耐心的,真是让人太遗憾了,我今天又试了好几十遍,让我看到是的的确确存在共享存储空间的问题.数组里面所有变量值相同的,java中仅用一个存储空间.但是大家可能做实验不一定做得出来,因为我把那段代码取出来单独运行的时候却是正常的,但不知道为什么在这个程序里面就出现共享,我现在有点怀疑是不是java编译器有内部的优化措施,也许看到代码太长,存储空间又不是很充足,然后编译器就自作主张,把变量值相同的全部换为一个地址来存放.我不知道是不是这样?这么久了竟然没几个人来仔细看一下这个问题,都是粗浅地,青蜒点水一样地说些无实际作和的东西.我恳请高手们来看看这个问题,其实并不需要看懂整个程序,只需在mutate()函数中的这条语句
    population[i].gene[j] = randval(lbound, hbound);前加上一个显示全部population里的值,再在其后也加上一个显示全部population里的值,你从前后的对比中就可以看到变化了,population[i].gene[j] = randval(lbound, hbound);只执行一次,但是population里的值却改变了很多个,照理应该改变一个才对的呀.我不知道这是为什么?我一直处于困惑中,找了许多资料也都没有提到这个问题.
      

  25.   

    你在抱怨什么啊?
    你总认为在mutate()函数中有问题,
    你在select()前后各加上一个显示全部population里的值,
    你自己看看!
    多看几次!
      

  26.   

    没仔细看,问题应该是出在select(), 按照你的程序population与newpopulation元素赋值有问题. 你那样赋值的话,最后population元素里的3个double数组都会分别引用同一组对象.你可以细化元素的赋值,也可以让GT类实现Cloneable,再调用clone赋值.
      

  27.   

    wolf863292(kkk)兄弟,我看了,select()没有问题,你看到的结果也许是正确的,因为select()是选最优,有可能是前后全部一样的,但在mutate()函数就不同,因为其是变异,也就是改变其值,所以前后输出的应该是不同的值,但为什么之后却没有改变?建议你看mutate()这段,希望你仔细看看程序.
      

  28.   

    to leeya() 你说的可能是对的,可能是出现了这种情况,我一直以为是jdk在自动优化,不过具体怎么细化赋值不是很清楚,你可不可以写一段?
      

  29.   

    对于你这个问题,可以编写一个方法来细化赋值. 如void copyPopulation(GT sPopulation,GT dPopulation),将原元素的属性分别赋给目标元数,对于属性是数组的,也要数组元数分别复制.这种方法,思路简单,略显罗嗦. 我建议你用clone方法,符合面向对象编程思想,并且代码简洁! 你可以试一下下面的clone法:
    class Genotype implements Cloneable /* genotype (GT), a member of the population */
                {
            double gene[];
            double fitness;
            double upper[];
            double lower[];
            double cfitness;
            double rfitness;
            Genotype() {
                gene = new double[NVARS]; /* a string of variables */
                fitness = 0; /* GT's fitness */
                upper = new double[NVARS]; /* GT's variables upper bound */
                lower = new double[NVARS]; /* GT's variables lower bound */
                rfitness = 0; /* relative fitness */
                cfitness = 0; /* cumulative fitness */
            }
            
            public Object clone(){
               Genotype o = null;
               try{
                 o = (Genotype)super.clone();
               }
               catch(CloneNotSupportedException e){
         System.out.println("Can't support clone for GT");
      }
                
               o.gene = (double[])gene.clone();
               o.upper = (double[])upper.clone();
               o.lower = (double[])lower.clone();           return o;
            }    }最后,在你需要复制对象的地方, 这样使用:
    newpopulation[i] = (Genotype)population[j].clone();
    or
    population[i] = (Genotype)newpopulation[j].clone();Good luck!!!!!!!!!!!!!!!!!!!
      

  30.   

    leeya() 非常感谢您的帮助,确实是这个问题.呵呵,真是有点奇怪.在C++里那样的语句实现得多好,到了java中却还要用这种赋值方法.真的得非常谢谢你,你学java也有快两年了,头一回中碰到如此难缠的问题,由于这个贴分不多,你到下面的贴子回一个,我好给分给你。
    http://community.csdn.net/Expert/topic/5346/5346777.xml?temp=.5153314
    同时我也要感谢其它的各位程序员们,在这里,你们的关心和帮助我是不会忘记的,这是一个好地方,只要我们大家相互帮助,就没有什么问题解决不了的,这样我国软件产业的发展也会更快的!