2013-10-26 80 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

相关问题