我有2 ArrayList
s。第一個保留第二個ArrayList
中的元素應該如何排序的索引。如何使用ArrayList
1中的正確索引對ArrayList
2中的元素進行分組?Collections.sort with 2 array
我的代碼:
public void createRolette(Population population) throws Exception {
ArrayList<Integer> rouletteId = new ArrayList<Integer>();
ArrayList<Integer> rouletteFit = new ArrayList<Integer>();
for (int i=0; i<populationSize; i++) {
population.getIndividual(i);
Simulator.allocateTask(i);
rouletteId.add(i);
rouletteFit.add(calcFitness(i));
}
// Collections.sort(rouletteFit);
我的輸出:
[0,1,2,3,4,5,6,7,8,9,10,11,12, 13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32, 38,39,40,41,42,43,44,45,46,47,48,49] [90,86,86,86,86,86,86,86,86,86,86,86, 86,86,86,86,86,86,86,90,86,86,86,86,86,86,86,86,86,86,86,86,88,86,88,86,86, 86,86,86,86,86,86,86,86,86,86,86,86]
我正在嘗試使用此給定的解決方案,但代碼中存在一些我無法修復的錯誤。
public abstract class Roulette implements Comparable<Roulette>{
super(); //here says "Syntax error on token "super", Identifier expected"
int rouletteId;
int rouletteFit;
public Roulette(int rouletteId, int rouletteFit){
this.rouletteId = rouletteId;
this.rouletteFit = rouletteFit;
}
public int getId(){
return rouletteId;
}
public int getFit(){
return rouletteFit;
}
public static Comparator<Roulette> FitComparator = new Comparator<Roulette>() {
public int compare(Roulette r1, Roulette r2) {
int fit1 = r1.getFit();
int fit2 = r2.getFit();
//ascending order
return fit1.compareTo(fit2);
//descending order
//return fit2.compareTo(fit1);
}
};
public void createRoulette(Population population) throws Exception {
ArrayList<Roulette> rouletteList = new ArrayList<Roulette>();
for (int i=0; i<population.size(); i++){
population.getIndividual(i);
Simulator.allocateTask(i);
Roulette r = new Roulette(i, Simulator.calcFitness(i)); // here in "new Roulette says // - Multiple markers at this line
//- Cannot instantiate the type Roulette
//- Line breakpoint:Roulette [line: 48]
createRoulette(Population)
rouletteList.add(r);
}
Collections.sort(rouletteList, Roulette.FitComparator);
}
}
您是否正在尋找某種[地圖](https://docs.oracle.com/javase/8/docs/api/java/util/Map.html)?因爲我不知道你在努力達到什麼目的。 – Veluria
這是學習算法時的經典練習。 –
@LuiggiMendoza,你可以用英文向我們翻譯OP的要求,甚至更好地編輯和改進問題,這樣的要求是明確的? –