The class is very simple, the user passes a total amount of shares and the shares that are allocated to that total. Pretty straight forward. Here is the test case.
By following these rules, here is t
This does works. But we can do better. We can compared the objects and see if they are indeed correct. This can also helps us in future projects. As you can see, the class is immutable, which means that we can easily share this object without compromising the state. We can do this by overriding the "equals" method in the Share's class. But first, we need to remember the rule that the equals method implements the equivalence relation. It is:
- Reflexive: an object must be equals to itself
- Symmetric: any two objects must agree on whether they are equal
- Transitive: if one object is equal to a second and the second object is equal to a third, then the first object must be equal to the third.
- Consistency: if two objects are equal, they must remain equal for all the time, unless one (or both) of them is modified
- Non-nullity: all objects must be unequal to the invocation of o.equals(null)
Here is the class with the equals override:
Now we can compared the actual objects:
Much better, but according to Item 9 in Effective Java, we should always override hashCode when we override equals. Failure to do so will result in a violation of the general contract of Object.hashCode which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and HashTable. The good thing is that Eclipse can be a great tool. By just clicking on Source code > Generate hashcode and equals you get this: