Skip to main content

Implementing equals() or equals() and hashcode()

1 reply [Last post]
Joined: 2008-11-04


I'm implementing a solution in Java 1.5.0 and have some performance questions.

The aim is to store rule sets with one or more rules. The rule sets will seldomly be changed in the database.

Proposed solution:
My idea is to have a ArrayList with RulesSets. Each RuleSet in the ArrayList is a RuleSet class which has a field of type ArrayList that contains the rules related to the rule set. A number of strings on the RuleSet class makes it unique so not more than one rule set can have the same combination. The same goes for the Rule clss. Whenever I need to get information I have all variables making the key for the RuleSet.

Code example:
ArrayList rulesets = new ArrayList();

public ArrayList getRules(String keyPart1, String keyPart2) {
RuleSet rulesetGet = new RuleSet(keyPart1, keyPart2)
return rulesets.get(rulesets.indexOf(rulesetGet)).rules;
public class RuleSet {
public String keyPart1;
public String keyPart2;
public ArrayList rules = new ArrayList();

public RuleSet(String keyPart1, String keyPart2) {
this.keyPart1 = keyPart1; this.keyPart2 = keyPart2;

// Should implement equals() and/or hashCode() here?
public class Rule {
public String ruleType = "somevalue";
public String ruleValue = "anothervalue";
// Should implement equals() and/or hashCode() here?



1) My main focus is to write fast code. Is there any neglibale performance difference if I implement equals() or hashCode() in both/neither/one of the classes?

2) Is it best practice to override the objects equals(Object o ) and hashCode(Object o) using the same signatures, or is it okey to have for instance equals(RuleSet rs) and hashCode(RuleSet rs)?

3) If I were to use a HashMap instead, would the performance be better? (The key of the HashMap would be a class with two fields, keyPart1 + keyPart2, and the value a ArrayList/HashSet of Rules)

3) Do you see any other points on how to improve performance?

There will be approx 1000 rule sets, each of them containing about 10 rules.

Best Regards,

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2007-04-17

1) You'll have to measure it, but probably not.

2) You _must_ use the same signature or it won't override those methods (and won't get used). Use the @Override annotation introduced in Java 1.5.

3) Yes, the look up of the rule sets will be faster. Set the initial capacity to you expected number of rule sets.

4) Not off hand, but build it simply first then measure if it is good enough. If not, look where the problems are.