What Is Mutable Objects, How It Works In Java
In previous article, I explained about Immutable Objects in Java. Today I will talk about Mutable Objects
Let remember a little about Immutable Objects before we go to Mutable Objects in Java.
Immutable objects are objects whose state cannot be changed once they are created. Once you create an immutable object, you cannot modify its internal state (its fields).
Mutable Object is the inverse concept of Immutable Objects.
Mutable objects are objects whose state can be changed after they are created. You can modify the values of the fields of a mutable object. It mean you can change directly the original value and not create new Objects.
Most classes in Java are mutable by default. For example, ArrayList, HashMap, and custom classes with setter methods are mutable.
Example:
List<String> array = new ArrayList<>();
array.add("steve");
array.add("john");
array.add("david");
System.out.println(System.identityHashCode(array)); // Output: 112810359
Then I change the value of index 1 to be "Steve Loc"
array.set(0, "a1");
System.out.println(System.identityHashCode(array)); // Output: 112810359
The Output before and after change the value in Object is the same and that is Mutable Object
How to make a Mutable class?
Example:
领英推荐
public class MutableExample {
private int value;
public MutableExample(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
The question is, when in the MutableExample have one or more Immutable class like String or others, the MutableExample is still Mutable class or Immutable class?
The answer is: It still Mutable class wherever contain Immutable class
Example:
public class MutableExample {
private int value;
private String key; // String is immutable, but the reference can change
public MutableExample(int value, String key) {
this.value = value;
this.key = key;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
Advantages:
When to use it?
Thanks for reading <3
Please share your thoughts on the concept of immutable objects in Java in the comments right here ??
?Database Administrator | SQL, Oracle Database ?
2 个月Very helpful!