0

I do have an ArrayList with numbers and I need to get the greatest of them. I thought this would actually solve the problem, but it doesn't for negative numbers since greatest equals 0... Any help?


    public static int greatest(ArrayList<Integer> list) {

    int greatest = 0;

    for (int k : list)
        greatest = Math.max(k, greatest);

    return greatest;

Maciaz
  • 1,084
  • 1
  • 16
  • 31

3 Answers3

3

One simple solution is to start with the first element from your list or collection. This has the extra benefit that is type independent.

Make sure you handle 0 size array regardless of how you decide to move forward.

RailTracer
  • 88
  • 6
0

Get the first element of the list and make that the greatest.

int greatest = list.get(0);
user2023608
  • 470
  • 5
  • 18
-1

You can initialize greatest to minimum value of an integer as:

int greatest = -2147483648;
Ayush28
  • 359
  • 3
  • 18
  • There's a constant [`Integer.MIN_VALUE`](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#MIN_VALUE) for this. You don't need to put magic numbers in the code. – khelwood Sep 27 '17 at 08:48