0

Hi I'm having a problem to write a loop which finds the largest value.

A list of integers and an integer variable are declared like this: List list; int max; 

Assuming that some values (including negatives!) have been added to the list. i need to find the largest value in list and stores it in max.

//  start of test code

import java.util.*;

public class ListTest

{

private List<Integer> list;

private int max;
public void findMaxInListTest()
        {

list = new ArrayList<Integer>(); // could be a Linked list

list.add(0);
list.add(-99);

list.add(99);
list.add(1320);

list.add(470000);

list.add(12);
list.add(-5000);
list.add(300);
/*#     max = starting value

iterate through list to set max = max value in list

in this case 470000
    */

}

}

I tried using this loop but then encounter an error:

int max = list[0];
  for(int i=470000;i < list.length;i++){
    if(list[i] > max){
      max = list[i];
    }
  }
return max;

do you know which kind of loop that appropriate for this? Thanks

fareed
  • 2,954
  • 6
  • 34
  • 61
Ivana
  • 1
  • 1
  • 1
  • Welcome to Stack overflow, and check the [syntax formatting possibilities](http://meta.stackoverflow.com/editing-help). – Ondra Žižka May 31 '11 at 23:20
  • Hi Please see the answer here https://stackoverflow.com/questions/1484347/java-max-min-value-in-an-array – r0ast3d May 31 '11 at 23:18

5 Answers5

2

You need to iterate over the list. Start with i=0 - not 47000.

Hope this helps.

Adam Dymitruk
  • 117,004
  • 25
  • 140
  • 137
2
for(int i=470000;i < list.length;i++){

i is the index. put i=0. getting list element for index 470000 throws the exception.

also, list[i] doesn't work in java. use list.get(i). also, list.length doesn't work on lists. use list.size().

You're misinterpreting java List - it's not an array.

chemical
  • 771
  • 1
  • 6
  • 11
  • also make max = list.get(0); so you initialize your max, if a number in the list is bigger than the first item,then you replace max with that. – Balazs Gunics Jun 27 '13 at 08:26
2
import java.util.Collections;

Collections.sort(list);
System.out.println(list.get(list.size() - 1));
Eder
  • 1,854
  • 16
  • 34
1

No loop required, use max method from java.utils.Collections (Documentation)

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

public class Test {

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<Integer>();
        list.add(0);
        list.add(-99);
        list.add(99);
        list.add(1320);
        list.add(470000);
        list.add(12);
        list.add(-5000);
        list.add(300);

        System.out.println(Collections.max(list));
    }
}
moeTi
  • 3,814
  • 23
  • 35
1
for(int i=470000;i < list.length;i++){ 

should be

for(int i=0;i < list.length;i++){ 
DarthJDG
  • 16,331
  • 11
  • 48
  • 55
Brad Johnson
  • 71
  • 1
  • 2