| 1 | public class Weight implements Comparable<Weight> { |
| 2 | private int weight; |
| 3 | |
| 4 | Weight(int weight) { |
| 5 | setWeight(weight); |
| 6 | } |
| 7 | |
| 8 | public int getWeight() { |
| 9 | return weight; |
| 10 | } |
| 11 | |
| 12 | public void setWeight(int weight) { |
| 13 | if (validateWeight(weight)) { |
| 14 | this.weight = weight; |
| 15 | } else { |
| 16 | throw new IllegalArgumentException("Weight cannot be negative or zero"); |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | private boolean validateWeight(int weight) { |
| 21 | return (weight > 0); |
| 22 | } |
| 23 | |
| 24 | @Override |
| 25 | public int compareTo(Weight weight) { |
| 26 | int distance = weight.weight - this.getWeight(); |
| 27 | if (distance >= 0) |
| 28 | return distance; |
| 29 | else |
| 30 | return -distance; |
| 31 | } |
| 32 | } |