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)
getand aset,numbers.set(1, numbers.get(1) * 3)