I am using the list.add(index, element) function to insert elements into an ArrayList, where the index is not in order.
For eg,
first i call list.add(5, element5)
and then list.add(3, element3)
I am getting the exception java.lang.IndexOutOfBoundsException: Invalid index 5, size is 0 exception.
Please tell where I am doing wrong and how can I fix this.
You cannot add elements to indexes which do not yet exist. In general, as Japhei said, you can only add elements to indexes smaller or equal to the array length. This means, if your ArrayList is still empty, you can only add elements at index 0 or without specifying the index (which will just add it to the end).
What you want to do is initialize your ArrayList with empty elements. I normally use meaningless values like 0 or -1 for integers or empty strings depending on the array type (or null elements), and just fill them later.
But if you know how many elements you have, or what array size you need, why not just use a normal array? That would be the right way to do it.
The problem is that your ArrayList is empty and therefore the insert (via add(int index, E element) fails.
Consider using the add(E element) (documentation) to add the element to the end of the list.
You can only use indexes that are existing or one larger than the last existing. Otherwise you would have some spots with no element in it.
If you need a ficxed length to store elements on a specified position, try to fill the List before with empty entries or use an array:
MyElement[] myArray = new MyElement[theLengthOfMyArray];
myArray[5] = elementXY;
Or fill a List with null elements (shown here):
List<MyElement> myList = new ArrayList<>();
for (int i = 0; i < theTargetLengthOfMyList; i++) {
myList.add(null);
}
myList.set(5, elementXY);
So what is probably happening is, that you defined a size for your list on creating said list. According to your error message this would be 0. And on a list with the size 0, you can't set the 5th or 3rd position to anything, as they don't exist. If you would add the line where you define the variable "list", we could help you further!
You can't add to index not in list range:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())
See java doc:
https://docs.oracle.com/javase/8/docs/api/java/util/List.html#add-int-E-
Related
I'm trying to add a string into my array in the 3rd position because I need to do so for a loop I'm executing after it.
ArrayList<String> namesArray = new ArrayList<>();
namesArray.add(3, mString);
It gives an out of bonds expection, is this not possible to do?
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 0
When you say
arrayList.add(n, value);
the result is that after the add, arrayList.get(n) will have that value. You're trying to arrange things so that arrayList.get(3) will be mString. However, an ArrayList must be a list of consecutive elements; it can't be a "sparse array". That is, for arrayList.get(3) to exist, arrayList.get(0), arrayList.get(1), and arrayList.get(2) must also exist.
I don't know what you want those values to be (maybe null?), but you do have to set them. Java's ArrayList doesn't have an add method that automatically fills in the gap with a default value. You can add 3 nulls to the array like this:
arrayList.addAll(Arrays.asList(new String[3]));
You should fill the array with empty string before index 3 like this:
namesArray.add("");
namesArray.add("");
namesArray.add("");
Then you won't get that exception
I think it is a standard problem. I need a list that I can iterate for and backward. If iterating forward and the iterator riches e.g. 80% of length of the list, new element must be added to the end of list and the same number of elements must be deleted from the beginning of list. This should happen during iteration without influencing the iterator. The current iterator should be still valid. The same procedures should work, if the iterator goes backward.
Is there any kind of list, queue or stack in any collection that fulfills these requirements? Anybody know?
Thx
this can be very easily implemented using array.
Set initial size of the array.
Create Array of that size and you desired type
Create index (int for example) which is incremented/decreased when iterating the array.
Add logic to track the index (e.g. if index>0.8*size -> add more elements to the array)
I would use the java ArrayList object for this job.
What you are talking about is not an endless list, but a circular list (endless list would not delete from the beginning).
What you want is a function with a normal list inside, that takes an iterator as parameter and just rolls over when it reaches the end. So element 101 of 100 element list, is element 1 being overwritten.
A simple question: I store some values at an ArrayList at specific positions (indexes). These values are frequently updated by the code. My question is, in order to keep the ArrayList updated, it is sufficient to add the new value at the proper index (i.e. this action overwrites the older value stored there?) or do I have to remove first that value stored in that position of the ArrayList and then add the new value at this (now empty) position in the ArrayList?
The JavaDoc says...
set public E set(int index,
E element) Replaces the element at the specified position in this list with the specified element. Specified by: set in interface
List Overrides: set in class AbstractList Parameters: index -
index of the element to replace element - element to be stored at the
specified position Returns: the element previously at the specified
position Throws: IndexOutOfBoundsException - if the index is out of
range (index < 0 || index >= size())
So, basically, you can simply override the value at a specific location...
You may also want to take a look at Collections
I'm trying to increase the size of an array list but it doesnt seem to want to work.
I am doing this:
final int QUEUE_CAPACITY = 27;
ArrayList adjacencyList = new ArrayList<Integer>(QUEUE_CAPACITY);
But when I try to add something with the add that has two paramters, (index,value) I get this error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
You have established the initial capacity of the ArrayList, but there are still no items in the list. You can't insert an item before index 1 if it doesn't exist yet.
You must use the one-argument add method to append to the end of the list, or supply 0 as the index in the two-argument add method, so that there is something in the list.
Well, If you really want to do this.
You need to Intialise the Array with 'Integers' like '0' or so
and then instead of add() method use the set(int index, E element) method which Replaces the element at the specified position in this list with the specified element.
Any index at which you see '0' is equivalent to empty.
Are you calling the equivalent of adjacencyList.add(1, 1)? If so, you're trying to add to an empty list at index 1, which doesn't exist. Just call adjacencyList.add(<value>).
Also, include the generic type at initialization:
ArrayList<Integer> adjacencyList = new ArrayList<Integer>(QUEUE_CAPACITY);
PS. You don't usually need to adjust the initial capacity of an ArrayList unless you know the list will rarely end up being small.
That's not how it works.
If you're going to insert something at a certain position, you need to have elements stored up to the point in the list already.
Is there a way to remove all empty cells in an ArrayList by just a built in function call? I saw trimToSize but I didn't really get what it meant.
For example, suppose I have an array that contains {1,2,3}. Lets say I say array.remove(1) so now the array looks like {1,null,3}. Is there a function to call to make it converge to be {1,3}?
I know I can hard code a method to do that for me but I was just curious.
That's exactly what remove does.
Removes the element at the specified
position in this list. Shifts any
subsequent elements to the left
(subtracts one from their indices).
Now, if you're talking about arrays, not ArrayList, the answer is no.
If you are using an ArrayList, you don't need to worry about compacting the array after removing an element from it. The ArrayList class takes care of this kind of housekeeping.
If you are using an array, you could use the Commons Lang ArrayUtils class. The removeElement methods in this class simplify removing an element from an array and shifting all elements after it to the left.
In here you find a post that shows how to remove all null elements in a Collection
List<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(2);
myList.add(null);
myList.add(3);
myList.add(null);
myList.add(4);
System.out.println("With null values");
for(Integer i: myList)
System.out.println(i);
myList.removeAll(Collections.singleton(null));
System.out.println("After deleting null values");
for(Integer i: myList)
System.out.println(i);
Output:
With null values
1
2
null
3
null
4
After deleting null values
1
2
3
4