6

I have two different functions for trying to find the largest value in an 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. 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 );
Lion
  • 18,729
  • 22
  • 80
  • 110
James King
  • 2,425
  • 7
  • 30
  • 45

2 Answers2

9

Use already existing 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.

Marcin Szymczak
  • 11,199
  • 5
  • 55
  • 63
  • "slightly worse solution" depends on the application. If the `n` is large enough, say, 1 billion elements and let's assume 1 unit of work to process each, O(n log(n)) is something like 30 billion units of work, potentially pretty awful. – ggorlen Apr 04 '22 at 03:38
1

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);
}
Nathan Villaescusa
  • 17,331
  • 4
  • 53
  • 56
  • Ah yeah, I just copied that from the original example. I assumed they were checking beforehand whether the array was empty. – Nathan Villaescusa Oct 08 '12 at 19:44
  • 1
    You should store the size and not always call the method. A for each is also preferrable, regarding to effective java. – Christian Oct 08 '12 at 20:56