Handle ArrayIndexOutBoundException - java

I am facing Array Index OutboundException when runs the code..
My code here
public void putValuesForDeleteAction(HashMap map ,Object[] colNames,Object[] colValues,Object[] colDataTypes){
try{
if(colNames!=null && colNames.length > 0 && colValues!=null && colValues.length >0 &&
colDataTypes!=null && colDataTypes.length >0){
int i = 0;
i = colNames.length ;
colNames[i]="LAST_UPDATE_BY";
colValues[i]=(String)map.get("LAST_UPDATE_BY");
colDataTypes[i]="VARCHAR2";
i++;
colNames[i]="LAST_UPDATE_DATE";
colValues[i]=(String)map.get("LAST_UPDATE_DATE");
colDataTypes[i]="TIMESTAMP";
System.out.println("mapValues is "+map);
}else{
// do nothing
}
}catch(Exception e){
e.printStackTrace();
}
}
Error logs
2014-09-17 10:47:51.026 ERROR [STDERR] java.lang.ArrayIndexOutOfBoundsException: 9

ArrayIndexOutOfBoundException means it does not found any element at index position which you specifying
in your case you first assign object array length to i by i = colNames.length ;
suppose your array length is 4
means your array last index is 3 because index start from 0,1,2,3 total length 4
so replace
i = colNames.length ;
with
i = colNames.length - 1 ;
and again you are doing i++ which is again wrong statement
conclusion is ArrayIndexOutOfBoundException occurs when your i > array length

You can use System.arrayCopy to copy existing array to an array of more size and aviod the exception.
Below copyFrom is the original array and copyTo is the destination array of larger size.
System.arrayCopy(copyFrom, 0, copyTo, 0, copyFrom.length);

This piece of below code is causing problem.
colNames[i] = "LAST_UPDATE_BY";
colValues[i] = map.get("LAST_UPDATE_BY");
colDataTypes[i] = "VARCHAR2";
colNames[i] = "LAST_UPDATE_DATE";
colValues[i] = map.get("LAST_UPDATE_DATE");
colDataTypes[i] = "TIMESTAMP";
Once value of i is more than the array length, it will give this exception.
java.lang.ArrayIndexOutOfBoundsException
Eg: suppose length of any array is 2, so at max you can access [0] and [1], but if you try to access [2], it will throw the above exception.
Solution to your problem
Since you are trying to add new elements in all the three arrays, you must increase or set the size before hand.
Including on #Aryan request, just run below program and analyze
public static void main(String[] args) {
// declaring array of size 2, ie it will contain max 2 elements
String[] myArray = new String[2];
System.out.println("accessing 1 element");
System.out.println(myArray[0]);
System.out.println("accessing 2 element");
System.out.println(myArray[1]);
// while accessing 3rd element, it will give error, since size is defines as 2.
System.out.println("accessing 3 element");
System.out.println(myArray[2]);
}
I would suggest you use an ArrayList as you won't have to worry
about the length anymore. Once created, you can't modify an array
size:
An array is a container object that holds a fixed number of values
of a single type. The length of an array is established when the array
is created. After creation, its length is fixed.

Related

How to initialise an int java array of size n initially empty?

In a function,I want to initialise a java array of max size n, which is empty initially.If I add 3 elements(say n>3) and return the array, the array should contain only the 3 elements and not 3 elements followed by (n-3) 0's.
//PSEUDO CODE
func(){
//Create array A of max size 5
A[0]=1;
A[1]=2;
A[2]=3;
return A;
}
main(){
int[] B=func();
//B.length should give 3
for (int i=0;i<B.length;i++){
print B[i];
}
/*Should print 1 2 3
and Not 1 2 3 0 0
*/
}
And I don't want to use array list.I want to use java array only.
Your problem seems to be that you only want to print the non-default values of the array. If your values are always different from zero, then you can just do:
for (int i=0;i<B.length;i++){
if (B[i] != 0){
print(B[i]);
}
}
However, if your values can also be zero, you can also keep a counter of how many values you currently have, and only print that many values:
int counter = 3; //the array might be {1, 2, 3, 0, 0}
for (int i=0; i<counter; i++){
print(B[i]); //will print "1 2 3"
}
The counter must be incremented everytime you add a value.
Both solutions are limited though, depending on how you access and use the array.
then u have to make the array dynamic by urself. Everytime u add an element to the array create a new array of size=no of elements (let u r adding the 3rd element then size of new array would be 3). take the elements from old array to the new one. Each time u add 1 element u have to follow this.

Issue with ArrayList

This is a very basic example and I only used the existent methods.
import java.util.ArrayList;
public class A {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<Integer>();
// This should create an ArrayList of initial capacity 10
al.add(3,5); // Add 5 at index 3
al.add(7,2); // Add 2 at index 7
al.add(9,6); // Add 6 at index 9
System.out.println(al);
}
}
However, it throws the following exception:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 0
I don't know why the exception is thrown. It look perfectly legal to me.
You can't add a value at index 3 to an empty list. The capacity of an array list is the size of the underlying array; the indexes still have to be within the range of items actually added to the arraylist.
The relevant documentation is here
Note that it specifies an exception thrown if the index is greater than the size of the array ... which is different from the capacity.
The capacity does not mean there are 10 empty slots which you can assign your values to. This is not how ArrayList is supposed to work. You can put your values to the list only if the index is between 0 and list.size-1, this is why you are getting the exception.
Your code would try to find the element at index = 3, so that it could move it to next position. However, it can't find it as there is no element there.
See official docs for add(int index, E element)
it throws java.lang.IndexOutOfBoundsException: if the index is out of range (index < 0 || index > size())
Check that does your case satisfies conditions or not !!!
This will work
ArrayList<Integer> al = new ArrayList<Integer>();
// This should create an ArrayList of initial capacity 10
al.add(0,5); // Add 5 at index 0
al.add(1,2); // Add 2 at index 1
System.out.println(al);
Your case size() is 0. So you cannot put directly at al.add(3,5)

Why is my int[] array loop out of bounds?

Warning: I am very new to Java and programming in general. I'll try to be as clear as possible.
I am attempting to take a simple integer (inputnumber), convert it to a string (temp), create a new int[] array (numberarray), and loop through this int[] array, starting from the last digit, and print out the name of the digit.
I am rather sure that the conversion from integer to String to int[] array was functional due to Eclipse debugging, but am stumped as to why I am getting an ArrayOutOfBounds message from Eclipse for such a simple for loop. Any clues as to what I am doing wrong is appreciated.
String temp = inputnumber.toString();
int[] numberarray = new int[temp.length()];
for (int i=0;i<temp.length();i++) {
numberarray[i] = temp.charAt(i);
}
for (int i=temp.length();i>0;i--) {
if (numberarray[i]==1) System.out.print("one.");
if (numberarray[i]==2) System.out.print("two.");
if (numberarray[i]==3) System.out.print("three.");
if (numberarray[i]==4) System.out.print("four.");
if (numberarray[i]==5) System.out.print("five.");
if (numberarray[i]==6) System.out.print("six.");
if (numberarray[i]==7) System.out.print("seven.");
if (numberarray[i]==8) System.out.print("eight.");
if (numberarray[i]==9) System.out.print("nine.");
if (numberarray[i]==0) System.out.print("zero");
}
The Eclipse error message I am getting is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at jt.Intermediate8.main(Intermediate8.java:44)
Arrays are 0-indexed in Java. This means the last value is at index NUMBER_OF_ELEMENTS - 1
Therefore, in your for loop, you should change
int i=temp.length() // this is last index + 1 (since we are starting from 0)
To:
int i=temp.length() - 1 // this is last index
Also, as #brso05 said, don't forget to change your loop-ending condition to i>=0 since the last value going backwards will be at index 0.
Your for loop:
for (int i = temp.length(); i >= 0; i--)
You're starting the loop at temp.length(). That's not a valid index. Perhaps you want temp.length()-1?
You should be doing temp.length() - 1. The reason is that the array starts with index 0 not 1 so the last element in an array is stored at the length - 1. If there are 10 elements then 0-9 are your indexes. Also change i>0 to i>=0 if you want to hit all elements.
for (int i=(temp.length() - 1);i>=0;i--) {

Checking to see if array is full

If I have an Array Candy[] type;
and type = new Candy[capacity];
if the Array is full is capacity = type.length ?
Since you are using array, the size of array is determined during compilation. Thus if your intention is to check whether current array's index has reached the last array element, you may use the following condtion (possibly in a loop) to check whether your current array index is the last element. If it is true, then it has reached the last element of your array.
Example:
int[] candy = new int[10]; //Array size is 10
//first array: Index 0, last array index: 9.
for (int x=0; x < candy.length; x++)
if (x == candy.length - 1)
//Reached last element of array
You can check the size of the array by using:
candy.length
You check whether it is last element by using:
if (currentIndex == candy.length - 1) //Where candy is your array
Make sure you are using double equal == for comparison.
Single equal = is for assignment.
Java creates an array with capacity count of references to the Candy instances initializing array with the nulls. So any array in java is full and
type.length == capacity
is always true.
type = new Candy[capacity] is equivalent to
type = new Candy[] {null, null, null, /* capacity count of nulls */, null};
In the example you show type.length will always be equal to capacity(after the initialization). Also your array will always have capacity elements but they will initially all be null.
If you want to check if array is full (no null elements), use something like this:
//1
boolean b = false;
//2
for(int i = 0; i < type.length; i++){
if(type[i] == null){
b = true;
}
}
//3
if(b == false){
System.out.println("Array is full");
}
What does it mean?
//1. At beginning you have one boolean (b) which is false.
//2. If any value in your array is null, b will be true.
//3. You check if value of b is still false. If it is, that means that b is never changed, so array is full (no null elements) .

Java ArrayList is throwing IndexOutOfBoundsException. Why?

This is my current progress on a project. I am trying to implement this ArrayList stuff but file continues to trow the same exception.
import java.util.*;
public class Numerican{
public static void main( String [] args ){
Scanner input = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<Integer>(10);
int count = input.nextInt() * 2;
while (count > 0){
array.add( 0 );
count = count - 1;
array.add(count, 2);
}
array.add(2, input.nextInt());
System.out.println(array.get(2));
}
}
It was my understanding that = new ArrayList<Integer>(10); would set the array size to 10. Did I do something wrong?
= new ArrayList<Integer>(10);
This line initializes the CAPACITY to 10, meaning the memory is allocated in the backend, but as far as you are concerned, the array is still empty.
Javadoc -
public ArrayList(int initialCapacity)
Constructs an empty list with the specified initial capacity.
This is why the calls to add might fail, if you try to add beyond the size of the ArrayList.
p.s. remember that add function takes index first and then element, when using the 2 parameter variant.
Edit:
ArrayList has 2 different member variables, size and capacity. Capacity is how much memory is allocated, size is how many elements are inserted by programmer.
Here, Capacity = 10, Size = 0;
According to the javadocs:
Constructs an empty list with the specified initial capacity.
Note that the ArrayList is empty (i.e. does not contain any items). The value indicates the capacity of the ArrayList which is the number of elements which can be added before more memory must be allocated.
On the other hand, calling add() actually adds an item to the ArrayList. In your example, array.add( 0 ); adds a 0 at the end of the list and array.add(count, 2); adds a 2 at index count. I suspect the problem is that count is not a valid index in your ArrayList. You should check what its value is by inserting an SOP or using a debugger.
count maybe >= 10, maybe souce code can answer you question:
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
rangeCheckForAdd():
/**
* A version of rangeCheck used by add and addAll.
*/
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
if the index is out of range (index < 0 || index > size()) IndexOutOfBoundsException will be thrown.
So i think you are accessing index > size() of the list.
size() ===> Returns the number of elements in this list.
array.add(2, input.nextInt()); here is the possible exception when your list size is 1...
From my understanding of ArrayList, you need to add items to the list in a sequential index.
i.e. You cannot add an item to the 7th index position if 1 to 6 have not been filled in.
ArrayList.add(indexPosition, element);
If you add elements to the list, starting at indexPosition 0, and increasing the indexPosition by 1 each time, it should work.
Ex.
int i = 0;
(while i < 10){
array.add(i, numberToAdd);
i++; }
Hey seems like your Problem is because of the line
array.add(count, 2);
adds a 2 at index count
For example your input size is 5 then array.add(9,2); the array size is only 1 by that time as capacity and size are two different parameters for a ArrayList. So you can use a for loop instead of while to insert your values
for(int i=0; i<count;i++)
{
array.add(i,2);
}

Categories