Finding the highest value in an ArrayList

I have two different functions for finding the highest value in an ArrayList. I have two, since I first saw if they would return the same value, and then the runtime.

However, they reproduce the same value, but it seems to be the last value of the ArrayList, regardless of whether it is the largest or not. I think that instead of the value you can take the key.

The code is below and I think this is a simple mistake, but can someone 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 ); 
+4
source share
2 answers

Use an 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 be seen 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 

The second approach can be useful if you need a sorted list later.

+6
source

You might be lucky if you keep the index that contains the largest number:

 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); } 
+1
source

Source: https://habr.com/ru/post/1438486/


All Articles