java - forEach() does not respect ordering, but here it seems to respect, why? -
i have been trying little basic ga implementation myself. used class gene wraps binary bit, chromosome class has arraylist named genes of gene objects. in chromosome class have evaluation method value() computes decimal equivalent of bits in chromosome. overridden tostring() method in chromosome class uses lambda expression create string representation of bits in gene objects contained in arraylist genes. question is: since foreach() method not supposed respect ordering (for benefit of parallelism), why return correct string representation of underlying bits, i.e. in order in created? or missing serious here? may because of short chromosome length, 'disrespecting' of ordering not prominent here?
here classes.
the gene class
public class gene { private short value; public gene() { value = (short) (math.random() <= 0.5 ? 0 : 1); system.out.print(value); } @override public string tostring() { return string.valueof(value); } } the chromosome class
import java.util.arraylist; import java.util.arrays; public class chromosome { private arraylist<gene> genes; public chromosome(int numofgene) { this.genes = new arraylist<>(); (int = 0; < numofgene; i++) { this.genes.add(i, new gene()); } } public int value() { return integer.parseint(this.tostring(), 2); } @override public string tostring() { stringbuilder chromosome = new stringbuilder(""); genes.stream().foreach((g) -> chromosome.append(g)); return chromosome.tostring(); } public static void main(string[] args) { chromosome c = new chromosome(10); system.out.println(""); system.out.println(c); } } the print statement in gene constructor see order in genes created. no matter how many times run program, foreach() gives correct representation of bits, confusing me. or ignorant of how supposed work, know not :-(
since using sequential stream, order of input list preserved. if change to
genes.parallelstream().foreach((g) -> chromosome.append(g)); you different order.
Comments
Post a Comment