0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HashMapでDTOを扱うときに必要なequalsとhashCodeの考え方

Posted at

Javaで HashMap を使うとき、DTO(Data Transfer Object)をキーや値に使う場合は、equals() と hashCode() の挙動を正しく理解しておくことが重要です。本記事では、DTOを含むHashMapの比較やキー・値として使う場合の注意点をまとめます。

なぜequalsとhashCodeが必要か

HashMap は内部で次の2段階で要素を管理しています:
hashCode() でバケット(格納位置)を決定
バケット内で equals() によって同一キーか判定
そのため、DTOをキーにしたMapでは、両方のメソッドを適切に実装していないと、Mapの比較や検索が正しく行えません。

まとめ

DTOを キー にする場合 → hashCode() と equals() の両方を実装
DTOを 値 にする場合 → equals() だけでMap比較可能
HashMapの比較や検索を正しく行うためには、DTOのメソッド実装が必須

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?