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.
Related
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-
Say I have a list of elements whose size is 100. Now I only want the 100th record in the list and the rest of all records from 1-99 should be removed from the list.
I have tried the below piece of code but no change in list size as I see it.
//Output list.size() returns 100
list.subList(list.size()-1, list.size());
//Output list.size() returns 100 after subList() called...
How can I get just the last record in the java.util.List using subList() or using any other methods available in Java?
list.subList returns a new List backed by the original List.
You need to store the returned list in a variable in order to use it:
List<String> subList = list.subList(list.size()-1, list.size());
subList.size() will be 1. list will remain unchanged.
If you want to remove all but the last element from the original List, you can write:
list.subList(0, list.size()-1).clear();
Now the original List will contain just 1 element.
ArrayList.subList method returns a sublist of your list without modifying your existing list.
So you need to do;
list = list.subList(list.size()-1, list.size());
To get just last record without changing list you could use:
element = list.get(list.size()-1);
this will work for any list, most effective for ArrayList implementation.
You can do it by importing com.google.common.collect.Iterables, but be aware if list is empty it will throw NoSuchElementException.
public MODEL getLastEntry(List<MODEL> list) {
return Iterables.getLast(list);
}
You can also use stream for it: https://www.baeldung.com/java-stream-last-element
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.
private JEditorPane textArea[]= new JEditorPane[maxTabs];
I've got this table,I want to delete some elements and move the others, for example if I delete the second element, the third will be instead of the second and so on.
Depending on scenario you are interested (we remove for example element at position 1)
1) If elements should be shifted to left and last element should be set to 0 or null depending on type of array like
before [0,1,2,3,4]
after [0,2,3,4,0]
you can use
System.arraycopy(textArea, index+1, textArea, index, textArea.length-index-1);
array[array.length-1]=null;
2) when you want to replace old array with new one that wont contain selected element like
before [0,1,2,3,4]
after [0,2,3,4] //we removed element at position 1 (new array is smaller)
you can try something like this
List<JEditorPane> listCopy = new ArrayList<JEditorPane>(
Arrays.asList(textArea));
listCopy.remove(index);
textArea = listCopy.toArray(new JEditorPane[listCopy.size()]);
You can use System.arraycopy() to move chunks of arrays around: see https://stackoverflow.com/a/5536023/150001
If you can, though, consider using a Collection class like java.util.LinkedList, which is much better suited to removing and reordering elements. If you still need an array when you're done with your deletions/moves (maybe the API you're working with requires it), you can use the toArray() method.