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
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-
I have a List of objects in Java, I want to insert an object at index - 1 of the first matched object.
How do that using RXJava? I have read Observable.first() but it only get me the first matched object, no index. Thus, I have no reference of where to insert.
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.
is it possible to retrieve the next (next, as in the next key value which has been inserted) key value of a LinkedHashMap?
E.g. the current key value is 2 and the next key value is 4. I want to use the value of the next key without setting my iterator (or whatsoever) one index further. Apparently using one iterator doesn't seem to do the job. Another idea would be to cast the set returned by myHashMap.keySet() to some other implementing class but I am not sure if it is possible to retrieve the next element.
Any ideas?
Assume there is LinkedHashMap<K,V> linkHashMap, now define a custom method getNextKey which takes a parameter index and return the next index value if valid.
Code snippet (not working code)-
public K getNextKey(int index){
// put check if index is valid
K[] keyArray = linkedHasMap.keySet.toArray(new K[linkedHasMap.size()]);
return K[index+1];
}
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.