I have a problem with sorting an ArrayList
of my own objects.
My class of these objects looks like that:
public class Robal {
int[] gen = new int[5];
int fit;
Random losuj = new Random();
public Robal(int przelacz) {
for (int i=0; i<5; i++ ) {
gen[i]=losuj.nextInt(2);
}
fit=dopasuj(gen, przelacz);
}
int dopasuj(int[] gen, int przelacz) {
int toDec=(gen[0]*1)+(gen[1]*2)+(gen[2]*4)+(gen[3]*8)+(gen[4]*16);
return y(toDec, przelacz);
}
int y(int toDec, int przelacz) {
if (przelacz == 1) {
return toDec*toDec;
} else if (przelacz == 2) {
return 1;
} else if(przelacz == 3) {
return 1;
} else if(przelacz == 4) {
return 1;
} else {
return 1;
}
}
void drukuj(int i) {
System.out.println("Geny Robala "+i+": "+gen[0]+" "+gen[1]+" "+gen[2]+" "+gen[3]+" "+gen[4]+"\tfit:"+fit);
}
}
and My Main class is:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class PE {
public static void main (String[] args){
ArrayList<Robal> Robale = new ArrayList<Robal>();
int i=0;
while(i!=5){
Robale.add(new Robal(1));
i++;
}
Robale.get(0).drukuj(1);
Robale.get(1).drukuj(2);
Robale.get(2).drukuj(3);
Robale.get(3).drukuj(4);
Collections.sort(Robale, new Comparator<Robal>() {
public int compare(Robal a, Robal b){
return a.fit - b.fit;
}
});
Robale.get(0).drukuj(1);
Robale.get(1).drukuj(2);
Robale.get(2).drukuj(3);
Robale.get(3).drukuj(4);
}
}
but most of the time the Data before and after sorting is not the same... example result:
Geny Robala 1: 0 1 1 0 0 fit:36
Geny Robala 2: 1 0 1 0 1 fit:441
Geny Robala 3: 1 1 0 0 1 fit:361
Geny Robala 4: 0 1 1 1 0 fit:196
Geny Robala 1: 0 1 1 0 0 fit:36
Geny Robala 2: 0 0 0 1 0 fit:64
Geny Robala 3: 0 1 1 1 0 fit:196
Geny Robala 4: 1 1 0 0 1 fit:361
Cœur
39k25 gold badges206 silver badges281 bronze badges
asked Dec 6, 2011 at 14:48
2 Answers 2
Are you sure you are not instantiating new Robal while sorting the list? that would cause the random values to shift
1 Comment
Adrian Modliszewski
Ok problem found... here: while(i!=5){ wrong number... I had 5 instances of Robal...
You are adding 5 items to the array and printing only 4 before and after sorting. It seems that 5th item in unsorted list made it to the top 4. Can you print one more item and see if things look good?
answered Dec 6, 2011 at 15:17
Comments
lang-java
1 0 1 0 1 fit:441
to having a0 0 0 1 0 fit:64
?