0

I know that the below code will give the greatest value in an Array, but why?

public class Practice {
  public static int greatest(ArrayList<Integer> list) {
  int greatest = list.get(0);
  for(int i: list){
    if(i > greatest){
        greatest = i;
    }
}
 return greatest;
}

public static void main(String[] args) {
     ArrayList<Integer> list = new ArrayList<Integer>();
     list.add(3);
     list.add(5);
     list.add(2);
     list.add(7);
     list.add(8);

System.out.println("The greatest number is: " + greatest(list));
}
}

If it is comparing the first value indexed in the list to another value that is greater than it while looping, wouldn't it would choose 5 instead of 8? How does it know to choose 8 instead of 5?

Thank you very much.

  • 1
    Because that's what `>` does? I'm not sure why you're confused. But this is a small enough program that you can pretend to be the computer and go through it with a pencil and paper to see how it works. – ajb Jun 28 '17 at 03:51
  • It's not comparing the index, it's comparing the value, `for(int i: list){` is an enhanced loop which is using the `List`'s `iterator` or get the next value from the `List` on each loop and assign it to `i` – MadProgrammer Jun 28 '17 at 03:51
  • In each iteration of the loop, your code checks if the `ith` number is greater than the largest number we have already seen. If so, then it overwrites `greatest` with that new largest value. You could step through your code with a debugger to see all this in action. – Tim Biegeleisen Jun 28 '17 at 03:51
  • I think you didn't get `Enhanced for loop`. – choasia Jun 28 '17 at 03:52
  • By the way, if you have a sorted array, consider using binary search, which would be much faster than your current approach. – Tim Biegeleisen Jun 28 '17 at 03:52
  • Or if you're just after the largest number (in a sorted `List`), just get the last value :P – MadProgrammer Jun 28 '17 at 03:53
  • I think it's time to step through the code one line at a time in your debugger. If you don't know how to do this, now is the time to learn. The sooner you lean the debugger the sooner you can begin answering questions like this yourself. – Jim Garrison Jun 28 '17 at 04:10
  • I was confused, i just realized that greatest was just assigned to a number which in this case was the index of 0. I set it equal to 0 and 5 which gave the same result. Thank you. – Steve Daniel Jun 28 '17 at 04:14

1 Answers1

0

Read about enhanced for loop or foreach loop in java.

You will have an array value in variable i, not the index.

abstractnature
  • 456
  • 2
  • 9
  • If you're gonna tell someone to read up on something, giving them a pointer would be nice. Here's some: [JDK docs](https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html), [StackOverflow](https://stackoverflow.com/q/85190/113632), [Wikipedia](https://en.wikipedia.org/wiki/Foreach_loop#Java). – dimo414 Jun 28 '17 at 04:23