###何をしているか理解したいです。
参考書を読み進めていると、コードの中で何の処理をしているのかイマイチ理解できない箇所が出てきました。
参考書の内容は、以下のコードを実装し、オブジェクトが同じ場合は hashCodeメソッドも同じ値を返すように修正する、というものです。
java
1@Override 2 public int hashCode() { 3 final int prime = 31; //なぜ31なのか? 4 int result = 1; //resultに1を設定 5 result = prime * result + employeeNo; // resultに31と1を掛けてemployeeNoを足している?? 6 result = prime * result + ((employeeName == null) ? 0 : employeeName.hashCode()); //?? 何をしているのかよくわからない。 7 return result; // 結果を返している・・・ 8 }
全体のソースコード
java
1public class Employee { 2 3 private int employeeNo; 4 private String employeeName; 5 6 public Employee(int employeeNo, String employeeName) { 7 this.employeeNo = employeeNo; 8 this.employeeName = employeeName; 9 } 10 11 @Override 12 public boolean equals(Object obj) { 13 if (this == obj) { 14 return true; 15 } 16 if (obj == null) { 17 return false; 18 } 19 20 if (getClass() != obj.getClass()) { 21 return false; 22 } 23 24 Employee other = (Employee)obj; 25 if (this.employeeNo != other.employeeNo) { 26 return false; 27 } 28 if (employeeName == null) { 29 if (this.employeeName != null) { 30 return false; 31 } 32 33 } 34 else if (!employeeName.equals(other.employeeName)) { 35 return false; 36 } 37 38 return true; 39 40 } 41 42 @Override 43 public int hashCode() { 44 final int prime = 31; 45 int result = 1; 46 result = prime * result + employeeNo; 47 result = prime * result + ((employeeName == null) ? 0 : employeeName.hashCode()); 48 return result; 49 } 50 51 52} 53
java
1import java.util.HashSet; 2import java.util.Set; 3 4public class Eaction { 5 6 public static void main(String...arge) { 7 8 Employee employee1 = new Employee(1 , "Mr.Yamada"); 9 Employee employee2 = new Employee(1 , "Mr.Yamada"); 10 11 Set<Employee> employees = new HashSet<>(); 12 employees.add(employee1); 13 employees.add(employee2); 14 15 System.out.println(employees.size()); 16 } 17}
補足情報(FW/ツールのバージョンなど)
eclipse使用
回答4件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/03/13 04:41