is an object with a string field mutable or immutable

In Java, strings are immutable objects. You might wonder if an object contains a String field which can be changed to other strings, is it an immutable or mutable object?

In fact, an object is considered immutable if its state cannot be changed after it is created. This means that all fields of the object must be final and cannot be modified after the object is constructed. Even though String objects themselves are immutable, if an object contains a field of type String that can be changed to reference a different String object, then the containing object is considered mutable. This is because the state of the object (i.e., the value of the String field) can change.

Here’s an example to illustrate this:

public class MutableObject {
    private String mutableField;  // fields without final can be changed

    public MutableObject(String initialField) {
        this.mutableField = initialField;
    }

    public void setMutableField(String newField) {
        this.mutableField = newField;
    }

    public String getMutableField() {
        return mutableField;
    }
}

In this example, MutableObject is mutable because the mutableField can be changed using the setMutableField method.

On the other hand, an immutable object would look like this:

public final class ImmutableObject {
    private final String immutableField; // final fields cannot be changed

    public ImmutableObject(String initialField) {
        this.immutableField = initialField;
    }

    public String getImmutableField() {
        return immutableField;
    }
}

In this case, ImmutableObject is immutable because the immutableField is final and cannot be changed after the object is created.

So, if your object allows its String field to be changed, it is considered mutable.

沒有留言:

Building a Lightweight Streamlit Client for Local Ollama LLM Interaction

Ollama 提供端點串接服務,可由程式管理及使用本地大語言模型(LLM, Large Language Model)。 以下程式碼展示如何以 Streamlit 套件,建立一個輕量級的網頁介面,供呼叫 本地端安裝的 Ollama 大語言模型。 Ollama 預設的服務...

總網頁瀏覽量