Java If Statement

我用Java编写了一些代码来测试两种解决方案的适用性。

我希望比较两种解决方案并保持最佳适应性并丢弃另一种解决方案。

例如:

if(fitness1 < fitness2) keep fitness1 and discard/ignore fitness2 else keep fitness2 and discard/ignore fitness1 

我将如何实现这一目标? 最终我希望有一个最佳健身水平的清单(大小n)。 我想我必须在每次迭代中将最佳适应度添加到某种类型的列表中?

我会说,创建一个ArrayList来保持最佳值并使用它:

 arrayList.add((fitness1 < fitness2) ? fitness1 : fitness2); 

这样你就会有一个最好的值列表。

 best = (fitness1 < fitness2) ? fitness1 : fitness2; 

?:三元运算符可能在这种决策过程中很有用。

如果您的最终目标是获得“前n个健身水平”的列表,那么您可能会有一个列表进入,对吧?

如果是这种情况,只需利用List的function:

 // takes a list of Doubles, returns 'top' levels public List getTopN(List allLevels, int top) { List sorted = new ArrayList(allLevels); // defensive copy Collections.sort(sorted, new Comparator() { @Override public int compare(Double left, Double right) { return left.compareTo(right); // assumes no null entries } }); return sorted.subList(0, Math.min(sorted.size(), top)); } 

介绍另一个变量。

输入 bestFitness

 if(fitness1 < fitness2){ bestFitness = fitness1; }else{ bestFitness = fitness2; } 

然后丢弃fitness1fitness2

或者使用Math.min

假设健身是一个int

 int fitness1 = 5; int fitness2 = 10; int bestFit = bestFit(fitness1, fitness2); //nothing needs to be done to explicitly discard fitness2. Just keep using bestFit //and let the GC worry about discarding stuff for you public static int bestFit(int f1, int f2) { return f1 > f2 ? f1 : f2 }