Search code examples
javaexceptionarraylistcompiler-errorsindexoutofboundsexception

Java Code That Prints Reverse of Given ArrayList


So I was trying to write a method which returns the reverse of given ArrayList but it gives me Index error and I don't know how to solve it. I appreciate your help. This is my code:

import java.util.ArrayList;

public class question2 {

public static ArrayList<Double> reverse(ArrayList<Double> arraylist) {
    ArrayList<Double> result = new ArrayList<Double>();
    for(int i=0; i<arraylist.size(); i++) {
        result.set((arraylist.size()) - 1 - i, arraylist.get(i));
    }
    return result;
}

public static void main(String[] args) {
    
    ArrayList<Double> doubles = new ArrayList<Double>();
    doubles.add(1.5);
    doubles.add(2.3);
    doubles.add(7.7);
    doubles.add(8.6);
    System.out.println(reverse(doubles));
    
}

}

And this is the error:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 0

Solution

  • public static ArrayList<Double> reverse(ArrayList<Double> arraylist) {
           ArrayList<Double> result = new ArrayList<Double>(arraylist.size());
            for(int i=arraylist.size()-1; i>=0; i—-) {
                result.add(arraylist.get(i));
            }
            return result;
         }
    

    Hope this will work!