解答例 - 実習課題3 - 1.コレクション
(実習課題3)
以下のオブジェクトの同一性を、「==」と「equals」メソッドで比較した場合の結果の違いを確かめなさい。またこれらのハッシュ値を確かめなさい。
String a = "test";
String b = new String("test");
String c = "te" + "st";
String d = "te" + new String("st");
String e = new String("te") + new String("st")
解答例
package com.techscore.utility.chapter1.exercise3;
/**
* EqualExample.java
* TECHSCORE Javaユーティリティ1章 実習課題3
*
* オブジェクトの同一性について、比較する。
* "equals"メソッドで比較した場合、全てのオブジェクトは「同一」と判断される。
* "=="で比較した場合、"test"と"te"+"st"以外は異なるものと判断される。
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
public class EqualExample {
static String testString[] =
{
"test",
new String("test"),
"te" + "st",
"te" + new String("st"),
new String("te") + new String("st")};
public static void main(String args[]) {
for (int i = 0; i < testString.length - 1; i++) {
for (int j = i + 1; j < testString.length; j++) {
System.out.println(i + ":" + j);
System.out.println("equals:" + (testString[i].equals(testString[j])));
System.out.println("== :" + (testString[i] == testString[j]));
}
}
}
}

