Home > Net >  Arrays.fill() - ArrayIndexOutOfBoundsException
Arrays.fill() - ArrayIndexOutOfBoundsException

Time:01-21

can someone explain to me why i get ArrayIndexOutOfBoundsException: Array index out of range??

I have simple array, for example: {1,2,3,4,5}, i want to fill in index from 0 to before the last one by 0 : updated array should be like that {0,0,0,0,5}.

I try to us :

 public static int[] makeLast(int[] nums) {

    int size = nums.length;
    Arrays.fill(nums, nums[0], nums[size-2] ,0);
    return nums;
}

Unfortunatelly it causes me an error as above.

CodePudding user response:

Read the corresponding java doc: the 3rd parameter is the last index to fill. So the method "fills" from the first given index to that index -1

So you have to pass the indexes you care about, not the current content at those indexes!

Arrays.fill(nums, 0, size-1 ,0);

And note, the exception messages would have told you that you tried to access an invalid index. So the real answer is: read the exception messages carefully, and: read the javadoc for the library calls you are using even more carefully.

CodePudding user response:

You can use this code its work with me

 public static int[] makeLast(int[] nums) {
        int size = nums.length;
        if (size != 0) {
            Arrays.fill(nums, 0, size - 1, 0);
        }
        return nums;
    }

CodePudding user response:

First, it is not working as substring to exclude the last index. It fills from first index given to second index given - included.

Second, if your input array is null, empty or contains only one entry, your method fails too.

And you pass the content there and not the actual index - so completely wrong use of the fill method.

if (nums == null) return null;
int size = nums.length;
if (size > 1)
  Arrays.fill(nums, 0, size-1, 0);
  •  Tags:  
  • Related