Alex Rivera | Logout

TreeSet and equals function

Asked 2010-09-07T03:15:13.493
11

There is a Java bean object which has implemented equals function based on certain criteria (Criteria A). I have a requirement to identify unique objects based on another criteria (Criteria B). Since the equals function uses criteria A, I can not use HashSet. So I thought of using TreeSet with my custom Comparator which is based on criteria B. My question is, Is it allowed to do like this? Any issues with this approach?

Thank you.

Edit
Report

2 Answers

1

If you perform search often and add elements rarely, consider keeping them in a List sorted by Criteria B and using Collections.binarySearch.

answered 2010-09-07T07:52:05.683
1

You can wrap them:

class BeanWrapper {

 ...

 public boolean equals(Object other) {
  return myBean.critB.equals(((Bean)other).critB);
 }

}

And put them in the set like that.

answered 2010-11-28T14:07:52.427

Your Answer