LoginSignup
0
1

More than 3 years have passed since last update.

JavaにおけるfinalとImmutableの違い

Posted at

JavaにおけるfinalとImmutableの違いって?

最近GuavaのImmutable Listを使う機会があったのですが、ふとImmutableとfinalの違いってなんだ?と疑問になって調べてみました。

Immutableの特徴

・オブジェクトの値そのものを変更することを禁止
・参照先を変更することは可能

finalの特長

・参照先の変更をすることを禁止
・変数の値そのものを変更することは可能

では、JavaではImmutableで代表的なStringとMutableなStringBuilderを使って検証してみます。

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
         final String str = "apple";
         final StringBuilder sb= new StringBuilder("ringo");

        str = str + "ringo"; //コンパイルエラー。Stringの+は参照先変更を伴う。
                String s = "ringo";
                str = s;             //コンパイルエラー 
        sb.append("apple");
        sb = new StringBuilder("ringo"); ///コンパイルエラー。参照先変更。
        System.out.println(str);
        System.out.println(sb);
    }
}

こうやって比較してみると割と単純ですが、finalは値が不変であることと勘違いしていたのと、意外と日本語記事がなかったので書いてみました。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1