I need to have a Set (HashSet) such that if I insert a pair (a, b) and if (b, a) is already in the set, the insertion would just be ignored. How to do this in Java?
Many thanks!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well, it depends on the
hashCode()andequals()method of yourPairclass. They need to ignore order.Setitself is a good example of a class which ignores order for equality–you can look at the code ofAbstractSet. If the order of the pair doesn’t matter even outside of equality comparison, you can just storeHashSets (each with two elements) in your set. It would be best to wrap it in a datatype: