2013-10-26 79 views
0

我正在驗證我的數據列表與文件中的數據在數據庫中,以避免在數據庫中重複插入,如果重複存在,那麼我想索引該文件中的記錄,上午使用下面的代碼,ArrayList的indexOf()在java中返回-1

List<StudentMaster> studentMasterListFromDB = studentMasterDao.getStudentList(); 
List<StudentMasterVO> studentMasterListFromFile = getStudentMasterListFromFile(); 

for(int index=0;index<studentMasterListFromDB.size();index++){ 
    StudentMasterVO studentMasVO = new StudentMasterVO(); 
    StudentMaster studentMaster = studentMasterListFromDB.get(index);  
    BeanUtils.copyProperties(studentMasVO, studentMaster);  
    int indexOfexistingRec = studentMasterListFromFile.indexOf(studentMasVO); 
    System.out.println("indexOfexistingRec :"+indexOfexistingRec); 


} 

但「indexOfexistingRec」值給出-1,而不是現有記錄索引的索引。

+4

'-1'建議您正在尋找的項目沒有被發現。 – devnull

+0

感謝您的回覆。在我的列表中,搜索記錄存在,但它顯示-1。 – user2507974

+0

對不起,這是BeanUtils.copyProperties()方法。 – user2507974

回答

3

您需要在您的StudentMasterStudentMasterVO類中實施hashCodeequals方法,以便它們將得到適當的相等比較。

如果您使用的是Eclipse(或任何其他IDE),那麼它可以爲您生成這些方法,只需選擇比較時要考慮哪些字段。

例如見本文,如果你不熟悉的概念:http://www.javaworld.com/community/node/1006

+0

感謝您的回覆,我已經爲StudentMaster和StudentMasterVO使用equals()和hashcode()。但我仍然有同樣的問題。即使我也檢查了hashcodes,hashcodes也是正確的。 – user2507974

+0

那麼,copyProperties是做什麼的? – siledh

+0

它是一個BeanUtils方法,只需將一個對象的值複製到anthoer對象中,在這裏從StudentMaster對象複製到StudentMasterVO對象。但我認爲這不是問題所在。 – user2507974

相關問題