devdar
devdar

Reputation: 5654

How To Prevent Duplicates In Object ArrayList

I have a custom object array list, the object must be in an array list however i have some duplicates in the list and i want to preform a check before i do an add to the list. How can this be achieved. The victimSocialSecurityNumber is unique. Under is my code:

CODE

while (rs.next()){

       Citizens victims = new Citizens();
       victims.setSocialSecurityNumber(rs.getInt("victimSocialSecurityNumber"));

       victims.setfName(rs.getString("victimFName"));

       victims.setlName(rs.getString("victimLName"));

       victims.setPhoto(rs.getString("victimPhoto"));

       victims.setName(rs.getString("victimFName") +" "+ rs.getString("victimLName"));


       crime.getVictims().add(victims);         

Upvotes: 0

Views: 2462

Answers (4)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

Assuming Citizens overrides equals, you can do it like this

 if (!crime.getVictims().contains(victims)) {
       crime.getVictims().add(victims);  
 }

though generally when duplicates are not allowed the solution is Set

If you have doubts how to override equals / hashCode read http://javarevisited.blogspot.com/2011/10/override-hashcode-in-java-example.html

Upvotes: 2

Knight Shao
Knight Shao

Reputation: 89

You can use a hash set to add the objects and convert it to an Arraylist. This can help you to check whether the victim is unique.

CODE

Set hashset = new HashSet();

while (rs.next()){

   Citizens victims = new Citizens();
   victims.setSocialSecurityNumber(rs.getInt("victimSocialSecurityNumber"));

   victims.setfName(rs.getString("victimFName"));

   victims.setlName(rs.getString("victimLName"));

   victims.setPhoto(rs.getString("victimPhoto"));

   victims.setName(rs.getString("victimFName") +" "+ rs.getString("victimLName"));

   hashset.add(victims);       

}

List list = new ArrayList(hashset);

Upvotes: 1

Adam LeBlanc
Adam LeBlanc

Reputation: 962

I could be completely wrong here, but wouldn't a for loop solve your problem? You could just compare what you are about to add to all the elements in the arraylist, and if there are no matches add it, and if there is don't?

Upvotes: 0

Martin V.
Martin V.

Reputation: 3710

you can convert arraylist to set and back to get rid of the duplicates or use directly structure which allows only sorted unique elements : LinkedHashSet

Upvotes: 3

Related Questions