Check out the set(int index, E element) method in the List interface
Check out the set(int index, E element) method in the List interface
You can replace the items at specific position using set method of ArrayList as below:
list.set( your_index, your_item );
But the element should be present at the index you are passing inside set() method else it will throw exception.
Also you can check oracle doc here
How to replace array element with respect to Index on another array without using inbuilt methods?
Which method is used to replace the element at a specific index in an ArrayList in Java? Question 6Select one: a. set() b. replace() c. modify() d. assign()
java - ArrayList replace element if exists at a given index? - Stack Overflow
java replacing elements of an array - Stack Overflow
Here's the code if anybody stumbles upon this post and wants to help
let arrValue = [1, 0, 0, 1, 1, 0, 1, 0, 0]; let arrIndex = [2, 3, 4, 7];
I can change the values with push method and cannot do it with respect to indices in arrIndex.
function indexSwitcher(arr){
newArr = [];
for (let i = 0; i < arr.length; i++){
if (arr[i] === 1){
newArr[newArr.length] = 0;
}
else{
newArr[newArr.length] = 1;
}
}
console.log(newArr);
}
indexSwitcher(arrValue );
//output: [0, 1, 1, 0, 0, 1, 0, 1, 1] The above solution works but I don't know how to make it work with respect to indices in second array which is arrIndex here.Please don't give the solution just the guidance so that I can work it on my own.
The final output should be [1, 0, 1, 0, 0, 0, 1, 1, 0]
arrayList.set(index i,String replaceElement);
If you're going to be requiring different set functionaltiy, I'd advise extending ArrayList with your own class. This way, you won't have to define your behavior in more than one place.
// You can come up with a more appropriate name
public class SizeGenerousArrayList<E> extends java.util.ArrayList<E> {
@Override
public E set(int index, E element) {
this.ensureCapacity(index+1); // make sure we have room to set at index
return super.set(index,element); // now go as normal
}
// all other methods aren't defined, so they use ArrayList's version by default
}