Issue
So here I have an array of numbers and I want to change the value of a specific index only.
ArrayList <Integer> numbers = new ArrayList <> ();
numbers.add(5);
numbers.add(10);
numbers.add(20);
I was trying to do something like
userNumbers.get(1 (* 3));
where 1
should be the index and I'd multiply the value in that index by 3 therefore will result as 30
since 10
is the 1st index. Tried searching up but no luck for me!
Solution
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)
Answered By - epicGeek
Answer Checked By - Marilyn (JavaFixing Volunteer)