Anonymous Overriding HashSet hashCode
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?
//开发者_如何学CHelp 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 HashSet
doesn't allow you to use custom equality/hash comparisons. Your attempt is overriding the hashCode
of the set rather than each item in the set.
If the package name is always an appropriate equality indicator, you can override hashCode
and equals
in ApplicationInfo
itself. Otherwise, I think your best bet is to probably to create a HashMap<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:
Map<String, ApplicationInfo> nameMap = new HashMap<String, ApplicationInfo>();
for (ApplicationInfo pkg : packages) {
nameMap.put(pkg.packageName, pkg);
}
In your code, this
is actually the instance of an anonymous class, not an ApplicationInfo
object. And you won't get what you want that way either.
Why don't you use a HashMap< String, ApplicationInfo >
instead, and index it by packageName
?
精彩评论