Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ ストリングプール、equals() メソッド | 文字列
Java基礎

bookストリングプール、equals() メソッド

メニューを表示するにはスワイプしてください

equals() メソッド

このメソッドはオブジェクトの比較に使用され、特に String オブジェクトでよく利用される。2つの同じ文字列変数を作成し、== を使って比較する例を見てみる。

Main.java

Main.java

copy
123456789
package com.example; public class Main { public static void main(String[] args) { String first = new String("string"); String second = new String("string"); System.out.println(first == second); } }

結果は false となる。これは == がオブジェクト参照を比較し、実際の値を比較しないためである。両方の文字列が "string" を含んでいても、メモリ上では異なるオブジェクトであり、String pool の外で生成されている。

String pool

String Pool はヒープメモリの一部で、文字列リテラルが格納される領域。リテラルを使って同じ値の文字列を作成すると、メモリ上で同じオブジェクトを参照する。

なぜ false になったのか?それは、new String("string") を使うことで string pool を回避し、新しいオブジェクトをメモリ上に作成したためである。String first = "string"; を使う場合、文字列は string pool に配置され、共有される。

コード例を見てみよう。

Main.java

Main.java

copy
1234567891011
package com.example; public class Main { public static void main(String[] args) { String first = "string"; String second = "string"; String third = new String("string"); System.out.println("Result of comparing first and second: " + (first == second)); System.out.println("Result of comparing first and third: " + (first == third)); } }

どのように動作し、どのオブジェクトがString Poolに存在するかを説明するについて考察。

String Pool内の文字列とそれ以外の文字列の値をどのように比較するか。これには、Javaが提供するequalsメソッドを使用し、Stringオブジェクトの参照ではなく値を比較。equalsの代わりに==メソッドで文字列を比較するサンプルコードについて考察。

Main.java

Main.java

copy
1234567891011
package com.example; public class Main { public static void main(String[] args) { String first = "string"; String second = "string"; String third = new String("string"); System.out.println("Result of comparing first and second: " + (first.equals(second))); System.out.println("Result of comparing first and third: " + (first.equals(third))); } }

これで正しい比較ができていることがわかります。

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 5.  7

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 5.  7
some-alt