简体   繁体   English

查找ArrayList中的最大值

[英]Finding the largest value in an ArrayList

I have two different functions for trying to find the largest value in an ArrayList. 我有两个不同的函数来尝试在ArrayList中找到最大的值。 I have two since i was first seeing if they would return the same value and then performance time. 我有两个,因为我第一次看到他们是否会返回相同的值,然后是性能时间。

However they are reproducing the same value but it seems to be the last value of the ArrayList, regardless if its the largest or not. 但是它们正在重现相同的值,但它似乎是ArrayList的最后一个值,无论它是否为最大值。 I think it might be taking the key instead of the value. 我认为它可能是关键而不是价值。

The code is below, and I think its just a simple mistake but can anyone point me in the right direction? 代码如下,我认为这只是一个简单的错误,但任何人都可以指出我正确的方向吗?

double highest = fitnessArray.get(0);

for (int s = 0; s <fitnessArray.size(); s++){
    if (fitnessArray.get(s)>highest)
        highest=fitnessArray.get(s);

}

System.out.println("highest fitness = " + highest 
                + " indoexOf = " + fitnessArray.indexOf(highest));

double highestFitness;

highestFitness = Collections.max(fitnessArray);
System.out.println("lowest fitness 2 = " + highestFitness );

Use already existing api 使用已有的api

Collections.max(arrayList);

Example

import java.util.ArrayList;
import java.util.Collections;

public class Main {

  public static void main(String[] args) {

    ArrayList<Integer> arrayList = new ArrayList<Integer>();

    arrayList.add(new Integer("3"));
    arrayList.add(new Integer("1"));
    arrayList.add(new Integer("8"));
    arrayList.add(new Integer("3"));
    arrayList.add(new Integer("5"));

    Object obj = Collections.max(arrayList);
    System.out.println(obj);
  }
}

Documentation 文档

You can also consider as a slightly worse solution 您也可以将其视为稍差的解决方案

Collections.sort(arrayList); // Sort the arraylist
arrayList.get(arrayList.size() - 1); //gets the last item, largest for an ascending sort

Second approach might be useful if you'll need sorted list later. 如果您稍后需要排序列表,则第二种方法可能会有用。

You might have better luck if you store the index that the largest number is at: 如果存储最大数字所在的索引,您可能会有更好的运气:

if (fitnessArray.size() > 0) {
    double highest = fitnessArray.get(0);
    int highestIndex = 0;

    for (int s = 1; s < fitnessArray.size(); s++){
        double curValue = fitnessArray.get(s);
        if (curValue > highest) {
            highest = curValue;
            highestIndex = s;
        }
    }

    System.out.println("highest fitness = " + highest + " indoexOf = " + highestIndex);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM