What is the reason for ArrayIndexOutOfBoundsException in my code? - java

I am implementing Graham Scan Algorithm for convex hull in Java.
I am getting this error while running the code. For input string: "10 18"
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Graham.SelectMin(Graham.java:110)
at Graham.GrahamScan(Graham.java:78)
at Graham.main(Graham.java:41)
Can anyone help me out to solve this error?
Thanks

java.lang.ArrayIndexOutOfBoundsException: 0
This means that you're trying to access an element of an empty array. (An array of size 0.)
You need to have a non-negative size of the array to be able to access element at index 0.
For reference, this code for instance, produces the same error:
int initialSize = 0;
int[] arr = new int[initialSize];
System.out.println(arr[0]);

it means that on line 110 of Graham.java you are trying to access an array index that is either < 0 or that is > the length of your array, can't tell exactly which array without code.
Also Graham.SelectMin(Graham.java:110) shows that you are naming method calls in a non-idiomatic Java way. In Java method calls should be in lowerCamelCase, such as Graham.selectMin();
In Java UpperCamelCase is reserved for ClassNames.

Related

java.util.ArrayList length and size different?

I'm getting periodic crash reports on the following line of code:
myList.get(myList.size() - 1)
Which wouldn't be that interesting if not for the stack trace:
java.lang.ArrayIndexOutOfBoundsException: length=22; index=-1
java.util.ArrayList.get ArrayList.java:439
com.myapp.ope.api.ApiManager$2.onResponse ApiManager.java:215
retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1 DefaultCallAdapterFactory.java:89
retrofit2.-$$Lambda$DefaultCallAdapterFactory$ExecutorCallbackCall$1$hVGjmafRi6VitDIrPNdoFizVAdk.run Unknown Source:6
Which seems to imply myList has a length of 22. So how is the index calculated at -1 (which means .size() would have reported 0)?
The ArrayList in Java 8 only checks if the index is greater than its size, throwing an IndexOutOfBoundsException if so. Otherwise array[index] is used to access the desired element of the array used to store the list elements. This will throw an ArrayIndexOutOfBoundsException if the index is out of range, using the length of the array in the message. The array will be substituted by larger one if needed, but it will never be changed to a smaller one - so it is normal that the array is larger than required.
In Java 9, the index check was changed: it uses Objects.checkIndex(), which checks both limits and uses the size of the list for the Exception message.
ArrayList is backed by an array internally and it dynamically adjusts internal array as needed and size variable is maintained as you add elements ( increments as you add elements and decrements as you delete elements).
say at some point underlying array of ArrayList is with the length 22 (could be empty array, i.e. no elements stored), when you try to access it with -1 index, it will throw the java.lang.ArrayIndexOutOfBoundsException
*try printing list size before accessing the list as well to see if the size is coming as 0 or not

declaring a column length of 0 in a 2d array

I was just wondering if it was legal to declare a 2d ragged array with one or more of the columns having a length of 0. If it was legal, what will it actually do?
The answer is yes, it is possible. But then there's another question, why would you consider doing this? The reason I ask this is think about what you're trying to do here. An array in which the columns are of length 0 is technically an empty 2D array. I will, however, show how to do what you're asking and what will happen.
int[][] arr = new int[2][0]; //initializing a 2x0 array, which is 2 rows of size 0
or if you're trying to make a jagged array
int[][] arr = { {},{2} }; //this is a 2d array in which the first row has zero columns and the second row has one column
But what happens when you try operating on this array? You surprisingly won't get a compiler error, but you will get a runtime error. Suppose I added this line of code and tried running the program,
arr[0][0] = 1;
The error I would get is this,
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
because I can't access any elements in a 2d array with columns of size 0.

ArrayList out of [duplicate]

I get a lot of IndexOutOfBoundsException from the any Arraylist I use. Most of the times it works fine but sometimes I get this annoying error on Arraylists i use on my project.
The main cause is always either
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 3, size is 3
or
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 0, size is 0
Help me understand the main cause of this error as no matter how many answers I've searched they don't completely help me.
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 3,
size is 3
It means you have ArrayList which having 3 elements where you can get each element like 0,1,2 positions. And you are trying to read 4th element which does not exists into ArrayList.
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 0,
size is 0
It means you have a empty ArrayList, and you are trying to read 1st element.
ArrayIndexOutOfBoundsException - Examples
An array-index out of bounds exception is a Java exception thrown due to the fact that the program is trying to access an
element at a position that is outside an array limit, hence the words "Out of bounds". In other words, the program is trying to
access an element at an index that is outside the array bounds. To understand array bounds, let us consider the following diagram:
The picture above contains an array that consists of 7 elements. Each element in the array has its own index/position. In Java, an index always starts with
0 and ends with the length of the array -1. For example, the array above consists of 7 elements, therefore it's indices start from 0 and end with 6 (7-1). Attempting
to access an element with an index less than 0 or more than 6 will cause Java to throw an ArrayIndexOutOfBoundsException.
Read more about ArrayIndexOutOfBoundsException - Examples, Causes & Fixes
When your ArrayList size is 3, you can access the items at position 0 1 and 2.
If you try to access the item at position 3, it will throw an IndexOutOfBoundsException.
So when you iterate through Arraylist, your for loop should be like this
for(int i=0; i< list.size(); i++){
Object data = list.get(i);
}
Your condition must be i< list.size()
It is as simple as it gets.
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 3,
size is 3
It says size is 3 and the index you are asking for is also 3. Array list start with 0 so the maximum index will be 2 if the size is 3.
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 3, size is 3
this means your arraylist size = 3, but you want to access index = 3 in arraylist.
You need to know the index start at 0 in arraylist so that if your arraylist size = 3 that means you can access index from 0 to 2 like this
arraylist.get(0)
arraylist.get(1)
arraylist.get(2)
Size count starts from 1,2,3.....
Index count starts from 0,1,2....
When your arry list size is 1. you get value using 0 index. if u send index value 1. its throw exception.

Understand Arraylist IndexOutOfBoundsException in Android

I get a lot of IndexOutOfBoundsException from the any Arraylist I use. Most of the times it works fine but sometimes I get this annoying error on Arraylists i use on my project.
The main cause is always either
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 3, size is 3
or
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 0, size is 0
Help me understand the main cause of this error as no matter how many answers I've searched they don't completely help me.
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 3,
size is 3
It means you have ArrayList which having 3 elements where you can get each element like 0,1,2 positions. And you are trying to read 4th element which does not exists into ArrayList.
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 0,
size is 0
It means you have a empty ArrayList, and you are trying to read 1st element.
ArrayIndexOutOfBoundsException - Examples
An array-index out of bounds exception is a Java exception thrown due to the fact that the program is trying to access an
element at a position that is outside an array limit, hence the words "Out of bounds". In other words, the program is trying to
access an element at an index that is outside the array bounds. To understand array bounds, let us consider the following diagram:
The picture above contains an array that consists of 7 elements. Each element in the array has its own index/position. In Java, an index always starts with
0 and ends with the length of the array -1. For example, the array above consists of 7 elements, therefore it's indices start from 0 and end with 6 (7-1). Attempting
to access an element with an index less than 0 or more than 6 will cause Java to throw an ArrayIndexOutOfBoundsException.
Read more about ArrayIndexOutOfBoundsException - Examples, Causes & Fixes
When your ArrayList size is 3, you can access the items at position 0 1 and 2.
If you try to access the item at position 3, it will throw an IndexOutOfBoundsException.
So when you iterate through Arraylist, your for loop should be like this
for(int i=0; i< list.size(); i++){
Object data = list.get(i);
}
Your condition must be i< list.size()
It is as simple as it gets.
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 3,
size is 3
It says size is 3 and the index you are asking for is also 3. Array list start with 0 so the maximum index will be 2 if the size is 3.
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 3, size is 3
this means your arraylist size = 3, but you want to access index = 3 in arraylist.
You need to know the index start at 0 in arraylist so that if your arraylist size = 3 that means you can access index from 0 to 2 like this
arraylist.get(0)
arraylist.get(1)
arraylist.get(2)
Size count starts from 1,2,3.....
Index count starts from 0,1,2....
When your arry list size is 1. you get value using 0 index. if u send index value 1. its throw exception.

ArrayIndexOutofBoundsException in QuickSort Implementation

I'm trying out an implementation of QuickSort but getting an
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at com.JavaReference.QuickSort.swap(QuickSort.java:50)
at com.JavaReference.QuickSort.randPartition(QuickSort.java:20)
at com.JavaReference.QuickSort.randSort(QuickSort.java:12)
at com.JavaReference.QuickSort.randSort(QuickSort.java:13)
at com.JavaReference.QuickSort.randSort(QuickSort.java:13)
at com.JavaReference.QuickSort.randSort(QuickSort.java:13)
at com.JavaReference.QuickSort.randSort(QuickSort.java:13)
at com.JavaReference.QuickSort.randSort(QuickSort.java:8)
at com.JavaReference.QuickSort.main(QuickSort.java:59)
Here's my source code[here.]
Im a newbie to programming so any advice on where Im going wrong would be appreciated.
EDIT:Added entire stacktrace
My suspect is line 30:
int i =left-1;
Since left is initially 0, i will become -1. Then on line 35 you call
swap(a,i,j);
and bang.
OK, from the stack trace it seems my first guess was wrong.
Second guess: from the stack trace it shows that the array is partitioned 4 times, and then at the 5th attempt the exception comes. It is thrown on line 50:
int temp= array[a];
a is the first parameter to swap. The call to swap on line 20 was
swap(a,right,randPivot);
thus right is -1 at that point. This value comes from here (line 13):
randSort(a,left,pivot-1);
If pivot is 0 at this point, shit happens. And it can become 0 since it is taken as a random value between left and right, inclusive. (And actually, that is a mistake, as for effective partitioning, pivot should fall between left and right, noninclusive.) Currently, the probability of pivot becoming 0 increases as the leftmost partition becomes smaller. You need to introduce a check for this (or, more generally, to detect array partitions of size 1, which can't be partitioned further), to stop the recursion in time.
java.lang.ArrayIndexOutOfBoundsException: -1 does always tell you you're trying to call an array at an index which doesn't exist in this array.
Here the value of a ( Try to do System.out.println(a) which will show you the value of a) becomes at one time of the excecution -1.
So you try to call array[-1] which causes the exception because the array begins at an index of 0.
you need to change your algorithm so your method swap will only be called with values int[] array, value between 0 and array.length-1, value between 0 and array.length
You are trying to access to the element of the array with the index -1. This always throws an Exception. Check that the index (a >= 0).
Just a hint. This function:
public static void randSort(int a[],int left,int right)
leads to infinite recursion (it will call itself forever). At some point you will call swap with arguments left=0 and right=-1 (because randPartition returns 0 at some point).
I think it does not make sense to allow the pivot to be either left or right. This is because pivot should be used to separate two parts of the arry to be sorted (divide and conquer). To be most efficient, both parts should be equal in size.
So if left and right differ only by one, you should end recursion anyway.
Well folks,
It was my bad earlier, Id missed a critical
\\\Other code
if(left<right){
int pivot=randPartition(a,left,right);// testing purposes
randSort(a,left,pivot-1);........
...
in the randSort() function, I guess this was making right go negative .Sorry for all the noise.

Categories