|
| 1 | +// collectiontopics/Equality.java |
| 2 | +// (c)2017 MindView LLC: see Copyright.txt |
| 3 | +// We make no guarantees that this code is fit for any purpose. |
| 4 | +// Visit http://OnJava8.com for more book information. |
| 5 | +import java.util.*; |
| 6 | + |
| 7 | +public class Equality { |
| 8 | + protected int i; |
| 9 | + protected String s; |
| 10 | + protected double d; |
| 11 | + public Equality(int i, String s, double d) { |
| 12 | + this.i = i; |
| 13 | + this.s = s; |
| 14 | + this.d = d; |
| 15 | + System.out.println("made 'Equality'"); |
| 16 | + } |
| 17 | + @Override |
| 18 | + public boolean equals(Object rval) { |
| 19 | + if(rval == null) |
| 20 | + return false; |
| 21 | + if(rval == this) |
| 22 | + return true; |
| 23 | + if(!(rval instanceof Equality)) |
| 24 | + return false; |
| 25 | + Equality other = (Equality)rval; |
| 26 | + if(!Objects.equals(i, other.i)) |
| 27 | + return false; |
| 28 | + if(!Objects.equals(s, other.s)) |
| 29 | + return false; |
| 30 | + if(!Objects.equals(d, other.d)) |
| 31 | + return false; |
| 32 | + return true; |
| 33 | + } |
| 34 | + public void |
| 35 | + test(String descr, String expected, Object rval) { |
| 36 | + System.out.format("-- Testing %s --%n" + |
| 37 | + "%s instanceof Equality: %s%n" + |
| 38 | + "Expected %s, got %s%n", |
| 39 | + descr, descr, rval instanceof Equality, |
| 40 | + expected, equals(rval)); |
| 41 | + } |
| 42 | + public static void testAll(EqualityFactory eqf) { |
| 43 | + Equality |
| 44 | + e = eqf.make(1, "Monty", 3.14), |
| 45 | + eq = eqf.make(1, "Monty", 3.14), |
| 46 | + neq = eqf.make(99, "Bob", 1.618); |
| 47 | + e.test("null", "false", null); |
| 48 | + e.test("same object", "true", e); |
| 49 | + e.test("different type", "false", new Integer(99)); |
| 50 | + e.test("same values", "true", eq); |
| 51 | + e.test("different values", "false", neq); |
| 52 | + } |
| 53 | + public static void main(String[] args) { |
| 54 | + testAll( (i, s, d) -> new Equality(i, s, d)); |
| 55 | + } |
| 56 | +} |
| 57 | +/* Output: |
| 58 | +made 'Equality' |
| 59 | +made 'Equality' |
| 60 | +made 'Equality' |
| 61 | +-- Testing null -- |
| 62 | +null instanceof Equality: false |
| 63 | +Expected false, got false |
| 64 | +-- Testing same object -- |
| 65 | +same object instanceof Equality: true |
| 66 | +Expected true, got true |
| 67 | +-- Testing different type -- |
| 68 | +different type instanceof Equality: false |
| 69 | +Expected false, got false |
| 70 | +-- Testing same values -- |
| 71 | +same values instanceof Equality: true |
| 72 | +Expected true, got true |
| 73 | +-- Testing different values -- |
| 74 | +different values instanceof Equality: true |
| 75 | +Expected false, got false |
| 76 | +*/ |
0 commit comments