Replacing a HashSet Java member

Do a remove before each add:

 someSet.remove(myObject);
 someSet.add(myObject);

The remove will remove any object that is equal to myObject. Alternatively, you can check the add result:

 if(!someSet.add(myObject)) {
     someSet.remove(myObject);
     someSet.add(myObject);
 }

Which would be more efficient depends on how often you have collisions. If they are rare, the second form will usually do only one operation, but when there is a collision it does three. The first form always does two.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)