0

I am working with collection in which I'm trying to reverse a list and getting error as :

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at com.java.commonMethods.CommonClass.rev(CommonClass.java:22)
    at com.java.commonMethods.CommonClass.reverse(CommonClass.java:27)
    at com.java.commonMethods.CallToCommonMethods.callToCount(CallToCommonMethods.java:24)
    at com.java.commonMethods.CallToCommonMethods.main(CallToCommonMethods.java:42)

and u can check the code to i'm using to reverse as:

public static <E> void rev(List<E> list) {
        List<E> temp = new ArrayList<E>();
        for (int i = 0; i <= list.size(); i++) {
            list.set(i, temp.get(list.size() - i - 1));
        }
    }

    public static void reverse(List<?> list) {
        rev(list);
    }

and simply this is the call :

List<Integer> listInteger = Arrays.asList(0,1,2,3,4,5);
        CommonClass.rev(listInteger);
        System.out.println(listInteger);

can anyone tell me the cause of problem? and please tell me how is it causing problem and how to fix this issue.. thanks.

bananas
  • 1,176
  • 2
  • 19
  • 39
  • @Tunaki i think you need to check the question and then mark as duplicate if you really know what I'm really trying to ask.. – bananas Jan 25 '16 at 12:15

1 Answers1

2

Your temp List is empty, so calling get on that List with any index will throw an IndexOutOfBoundsException exception.

I'm assuming you intended to initialize temp with the elements of the original List.

Therefore, change

List<E> temp = new ArrayList<E>();

to

List<E> temp = new ArrayList<E>(list);

As Keppil commented, the range of your loop should also be corrected, since list.size() is not a valid index in a List of size() elements.

Change

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

to

for (int i = 0; i < list.size(); i++)
Eran
  • 387,369
  • 54
  • 702
  • 768