I’m trying to use a HashSet to remove the duplicates from a list of ApplicationInfo objects and I’m trying to use more advanced ways to accomplish this than the good old loop and compare.
I’ve been recently learning about the anonymous abilities in Java and I’m trying to apply that here but I’m stuck. From what I understand, equals() simply uses the hashCode() method to determine equality and from what I could gather I would only need to override the hashCode() method.
Within the ApplicationInfo object is a field called packageName, a string, which is the ONLY field I want the HashSet to compare and exclude any duplicates.
Since I’m new to Java, I’d love some help understanding if I’m understanding this right and either way, how to do this. I realize I could extend HashSet and do it that way but I want to try this Anonymous deal so I learn something.
If I have a HashSet containing ApplicationInfo objects, how do I return a hashCode based on the packageName field?
//Help me fix the below idea please
HashSet<ApplicationInfo> hs = new HashSet<ApplicationInfo>() {
@Override
public int hashCode() {
// How do I do this sort of thing
return this.packageName.hashCode();
}
};
Unfortunately
HashSetdoesn’t allow you to use custom equality/hash comparisons. Your attempt is overriding thehashCodeof the set rather than each item in the set.If the package name is always an appropriate equality indicator, you can override
hashCodeandequalsinApplicationInfoitself. Otherwise, I think your best bet is to probably to create aHashMap<String, ApplicationInfo>mapping the name to package. Assuming it doesn’t matter which package you end up with for a particular name, you can just loop: