昨天在開發的時候,碰到這樣一個問題:我有一個ArrayList<ArtistEntity>的對象artistList,每次在加入對象時,我都對加入的對象artistEntity進行了判斷,如果artistList不包含artistEntity,才進行加入:





但運行的結果并不是如開始設計的那樣,頁面顯示表明artistList包含了兩個相同的ArtistEntity對象,這是什么原因呢?
我看了一下jdk關于這段的源代碼:










































修正:直接利用Eclipse重寫,右鍵/源代碼/生成hashCode()和equals(),選擇要包括在hashCode()和equals()方法中的字段:









































或者,在加入artistEntity對象,比較artistEntity的key值。我這里是另外用一個ArrayList<String> artistCodeList存放artistEntity的key值,如果artistCodeList不包含待判斷ArtistEntity的key時,才將artistEntity加入artistList:






