Search code examples
javaarraylistmode

Finding the Mode of an ArrayList Java


For the past few hours or so I've been trying to find the mode out of an ArrayList. In the program, you find the max, min, median, and mean as well. I've figured out all of those but I haven't been able to do the mode. I keep getting an IndexOutOfBoundsException. Here is my code so far:

public String getMode(){
  int mode = 0;
  int count = 0;

  for ( int i : file1 ){
    int x = file1.get(i);
    int tempCount = 1;

    for(int e : file1){
      int x2 = file1.get(e);

      if( x == x2)
        tempCount++;

      if( tempCount > count){
        count = tempCount;
        mode = x;
      }
    }
  }

  return ("The mode is " + mode);
}

The error I'm getting is:

java.lang.IndexOutOfBoundsException: Index: 181, Size: 108
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at FunNumber2.getMode(FunNumber2.java:75)
at FunNumber2Tester.main(FunNumber2Tester.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

Solution

  • This is your problem

    for ( int i : file1 ){
    

    change it to

    for ( int i = 0; i< file1.size() ; i++ ){
    

    This syntax

    for ( int i : file1 ){
    

    is giving you the iterated value of file1, meaning that if file1 = List([4,5,6]) then in the first iteration of the loop i == 4 not 0.

    Obviously this would apply to the second loop as well.

    Alternatively you could change

    for ( int i : file1 ){
      int x = file1.get(i);
    

    to

    for ( int i : file1 ){
      int x = i;
    

    And it would fix your problem. Hope that helps.