Let arrList be the ArrayList and newValue the new String, then just do:
arrList.set(5, newValue);
This can be found in the java api reference here.
Answer from HaskellElephant on Stack OverflowLet arrList be the ArrayList and newValue the new String, then just do:
arrList.set(5, newValue);
This can be found in the java api reference here.
list.set(5,"newString");
- Reference
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
Refer to the Java documentation whenever possible. This in particular.
numbers.set(1, numbers.get(1) * 3);
Personally, I think it is because "Integer" is an immutable class, which means you cannot change the value of an immutable object with its member method.
If you put Integer, Long , Float ,Double, Boolean, Short, Byte, Character, String and other immutable classes in the list, you cannot change the value instantly.
But if you put customized objects in the list , you can change the value.
Demo code:
public class RRR {
public static void main(String[] args) {
ArrayList <Hi> hiList = new ArrayList <> ();
Hi hi1 = new Hi("one");
Hi hi2 = new Hi("two");
Hi hi3 = new Hi("three");
hiList.add(hi1);
hiList.add(hi2);
hiList.add(hi3);
Hi hix = hiList.get(0);
hix.setName("haha");
System.out.println(hiList.get(0).getName()); // changed from "one" to "haha"
}
}
class Hi {
public Hi(String name) {
this.name = name;
}
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
See? The class Hi is not Immutable , you can change this value with "setName"
Back to the question, change this Integer object , you can:
- Copy the new value and origin values to a new list, if your list is not too large(not good).
- Delete the old element, then set the new value to the right index.(should consider thread safe problem)