Home > database >  Encountering IndexOutOfBoundsException while implementing ArrayList function in Java to reverse arra
Encountering IndexOutOfBoundsException while implementing ArrayList function in Java to reverse arra

Time:09-24

Given an array/list 'ARR' of integers and a position ‘M’. You have to reverse the array after that position. You do not need to print anything, it has already been taken care of. Just implement the given function. This is my problem statement. The following is the code I tried implementing.


public class Solution 
{
    public static void reverseArray(ArrayList<Integer> arr, int m)
    {
        
        int i=0,p=1;
        int n=arr.size();
        ArrayList<Integer> reverseArray=new ArrayList<Integer>();
        for(int j=0;j<n;j  ){
            reverseArray.add(0);
        }
        for(;i<=m;i  ){
            reverseArray.set(i, arr.get(i));
        }
        for(;i<n;i  ){
            reverseArray.set(i,arr.get(n-p));
        }
        for(int j=0;j<n;j  ){
            arr.set(i,reverseArray.get(i));
        }
    }
}

I'm getting runtime error as

Exception in thread  main  java.lang.IndexOutOfBoundsException: Index: 6, Size: 6
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at Solution.reverseArray(Solution.java:21)
    at Runner.executeAndPrintOutput(Runner.java:50)
    at Runner.main(Runner.java:61)

Content of arr={1, 2, 3, 4, 5, 6}

CodePudding user response:

First of all, your problem is that in the last loop you are using i, instead of j. Second, your logic seems faulty to me. Here is a simple solution I've programmed -

public static void reverseArray(ArrayList<Integer> arr, int m) {

    int i = 0, p = 1;
    int n = arr.size();
    ArrayList<Integer> reverseArray = new ArrayList<Integer>();
    for (i = m; i < n; i  ){
        reverseArray.add(arr.get(n - i - 1   m));
    }
    for (i = m; i < n; i  ){
        arr.set(i, reverseArray.get(i - m));
    }
}

CodePudding user response:

May be something like this? remove the print statements before submitting.

private void reverseArray(List<Integer> src, int pos) {
    int j = 0;
    Integer[] srcArr = new Integer[src.size()];
    Integer[] tarArr = new Integer[src.size()];
    src.toArray(srcArr);
    src.toArray(tarArr);
    for(int i=pos; i<srcArr.length; i  ) {
        j  ;
        int tarIndex = srcArr.length-j;
        int tarEle = srcArr[tarIndex]; 
        tarArr[i] = tarEle;
    }
    
    for(int i = 0; i<tarArr.length; i  ) {
        System.out.print(tarArr[i]   " ");
    }

}
  •  Tags:  
  • java
  • Related