This question already has answers here:
ArrayIndexOutOfBoundsException on a initialized Vector
(1 answer)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Initial size for the ArrayList
(17 answers)
Closed 4 years ago.
I've read the documentation and looked at scores of SO questions and still can't create a vector of vectors without running into the ArrayIndexOutofBounds exception. For some context, I am creating a matrix, where each slot contains a reference to an edge, representing a flight from a source to a destination . Following one SO response, I set up my vector as follows.
Iterator<Edge> iter = array.iterator();
private Vector<Vector<Edge>> matrix = new Vector<Vector<Edge>>(9);
for (int i=0;i<9;i++){
matrix.add(i,new Vector<Edge>(9));
}
while (iter.hasNext()) {
Edge e = iter.next();
int s = e.source; //row
int d = e.destination; //col
Vector<Edge> row = matrix.get(s);
int size = row.size();
row.add(d, e); // Array Out of Bounds Exception
}
I believe I have initialized my inner and outer vectors and don't understand why the size of the vector is still zero. Do I have to initialize all the elements to null before I can start putting and getting elements? I would really appreciate your help.
new Vector<Edge>(9) creates an empty Vector of capacity 9. Therefore, calling add(d,e) for such a Vector when d is not 0 will throw ArrayIndexOutOfBoundsException.
To initialize each row Vector with null values, use:
for (int i = 0; i < 9; i++) {
Vector<Edge> v = new Vector<>(9);
matrix.add(v);
for (int j = 0; j < 9; j++)
v.add(null);
}
Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero.
Parameters:
initialCapacity the initial capacity of the vector
Throws:
java.lang.IllegalArgumentException if the specified initial capacity is negative
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 12 months ago.
public static Groceries [] addGrocery(Groceries[] arr, String name, int price) {
int arrayLength = Array.getLength(arr);
System.out.println(arrayLength);
Groceries[] newGrocery = new Groceries[arrayLength + 1];
int arrayLength2 = Array.getLength(newGrocery);
System.out.println(arrayLength2);
int i;
for(i = 0; i < arrayLength; i++) {
newGrocery[i] = arr[i];
System.out.println("New item added" + i);
}
newGrocery[i+1] = new Groceries(name, price);
return newGrocery;
}
I have this method where I input an array containing 4 objects and it creates a new array of objects copying the previous 4 objects and then adding one more to the array. But I keep getting this exception.
The exception occurred because you're trying to add an element to an array index (i+1) that just doesn't exist, here:
newGrocery[i+1] = new Groceries(name, price);
Its because i has already been incremented by the for loop at the end to the last index value in the array, by doing i+1 you're trying to access the index = arrayLength2 which doesn't exist.
May be what you want is a List that is capable of expanding its size when a new element is added, unlike array which has a fixed size.
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
I'm writing a program for class where we hard code matrices in a driver class and put the matrix operations in a matrix class. I'm running into an issue where I get the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
I'm pretty sure that it's the second for loop but I can't think of what range to do to refer to the columns of the hard coded matrix in the driver class.
row and col are both instantiated in the Matrix class and I fixed the j++ but it still gives the same error even when I'm doing a 1x2 multiplied by a 2x3, for example
public Matrix mult(Matrix m) {
// TODO: Multiply the two matrices, store the value
// in a new matrix and return that matrix
Matrix m5 = new Matrix(new int[row][col]);
for (int i = 0; i < row; i++) {
for (int j = 0; j < m.myMatrix[0].length; j++) {
for (int k = 0; k < col; k++) {
m5.myMatrix[i][j] += myMatrix[i][k] * m.myMatrix[k][j];
}
}
}
return m5;
}
I do not see that row and col are being instantiated anywhere, so I'm guessing that you are using member variables of the Matrix class. Your resulting matrix shouldn't be the same size as the original matrix unless they are both square matricies. For example, if you multiply a 4X2 matrix by a 2X3 matrix, it should result in a 4X3 matrix. Wikipedia provides an example of this.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have been coding a basic method to take an array of strings, find the largest length and return a string array containing on values that are equal to the highest length of the array. I keep getting a null pointer exception and i am not sure why. The code is:
String[] allLongestStrings(String[] inputArray) {
int compare = 0;
int k = 0;
String[] use = new String[20];
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i].length() > compare)
compare = inputArray[i].length();
}
for (int j = 0; j < 20; j++) {
if (inputArray[j].length() - compare == 0) {
use[k] = inputArray[j];
k++;
}
}
return use;
}
for (int j = 0; j < 20; j++) {
if (inputArray[j].length() - compare == 0) {
use[k] = inputArray[j];
k++;
}
}
This will only work if inputArray has at least 20 elements. In the code above, you're doing the correct thing: for (int i = 0; i < inputArray.length; i++). I think you just need to change this second for statement to be the lesser of 20 or the length of inputArray.
inputArray doesn't contain 20 elements. Don't just throw out and hard code a length value for your the array you're going to return. Actually determine what the true length is going to be because you could be too low on that value and if your not then you could end up with a bunch of null elements.
If allowed use an ArrayList or String List object which doesn't require a preset length (size) instead of a 1D String Array which does require length initialization: List<String> list = new ArrayList<>();. You can simply just add to it with the List.add() method.
If you must use a Single Dimensional Array then use another for loop to determine how many string elements actually have the same length as what is held within the compare integer variable. Always iterate through the original array (inputArray). This for loop would be very much like your second for loop except you would increment a integer counter variable upon all elemental lengths that equal the value held within the compare variable.
Eliminate the formula in your if statement condition contained within your second for loop. I think (IMHO): if (inputArray[i].length() == compare) {...} should be sufficient, it's much easier on the eyes. ;)
Just a thought for pizazz....perhaps add the actual Array index to the string that is added to the 1D String array named used. Use a delimiter of some sort to separate the two.
This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 5 years ago.
I have the following code:
// Creates ArrayList with integers 0-9
ArrayList<Integer> intKeys = new ArrayList<Integer>();
for (int x = 0; x < 10; x++) {
intKeys.add(x);
}
// Creates iterator with integers 0-9
Iterator<Integer> allKeys = intKeys.iterator();
// Loops 10 times, each time obtaining a key to remove from the ArrayList
for (int x = 0; x < 10; x++) {
Integer key = allKeys.next();
intKeys.remove(key);
}
I understand that ConcurrentModificationException is thrown if an element of a collection is removed while the collection is being looped over, such as:
for (String key : someCollection) {
someCollection.remove(key);
}
but right now I'm looping over nothing - just an arbitrary number of times. Furthermore, the error line is interestingly Integer key = allKeys.next(); What could be the cause of this exception?
You cannot use the list's Iterator object at all when you are removing items while looping.
If you are removing all the items from the list:
while (!list.isEmpty()) {
Integer i = list.remove(0);
//Do something with the item
}
Otherwise, you can iterate without the iterator:
for (int i = 0; i < list.length(); i++) {
//Do something with the list
}
I am having a problem with one of my methods in my program. The method is designed to take 2 arraylists and the perform multiplication between the two like a polynomial.
For example, if I was to say list1={3,2,1} and list2={5,6,7}; I am trying to get a return value of 15,28,38,20,7. However, all I can get is an error message that says:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0.
I have provided the method below:
private static ArrayList<Integer> multiply(ArrayList<Integer> list1,ArrayList<Integer> list2) {
ArrayList<Integer> array =new ArrayList<Integer>(list1.size()+list2.size());
for (int i=0;i<array.size();i++)
array.add(i, 0);
for (int i = 0; i < list1.size(); i++)
for (int j = 0; j < list2.size(); j++)
array.set(i+j, ((list1.get(i) * list2.get(j))+array.get(i+j)));
return array;
}
Any help with solving this problem is greatly appreciated.
Change your first for loop to:
for (int i = 0 ; i < list1.size() + list2.size() ; i++)
array.add(0);
As you have it, array.size() is initially 0 so that first for loop is never even entered, so nothing is being added to array. An ArrayList's capacity is not the same thing as its size.
You may want to check there exist an element at (i+j) before you sum it up with. So do this
int elementAtLoc = 0;
if(array.size() > i+j && array.get(i+j) != null ){
elementAtLoc = array.get(i+j);
}
array.set(i+j, ((list1.get(i) * list2.get(j))+elementAtLoc));
And there is no need of this:
for (int i=0;i<array.size();i++)
array.add(i, 0);
Since we are taking care of setting 0 in the second loop itself. It saves you extra work of looping just to add zeros.
Take a look at these codes :
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
private transient Object[] elementData;
/**
* The size of the ArrayList (the number of elements it contains).
*
* #serial
*/
private int size;
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
public int size() {
return size;
}
At this time, you have to create an instance by constructor they do not have assign the variable "size" where it contains the number of actual elements. That's reason why you get this exception.