Spaces:
Running
Running
File size: 3,008 Bytes
cc4c404 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
We have previously used the equals method to compare String objects.
It is also possible to implement the method in own class.
This enables the COMPARISON of 2 OBJECTS created out of OWN CLASS.
Let's implement the method to class 'Point', which models a point in 2-dimensional coordinate system.
Toteutetaan siis metodi equals luokkaan Piste, joka mallintaa pistettä kaksiulotteisessa koordinaatistossa:
class Point {
private int x;
private int y;
//CONSTRUCTOR
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
// If same object, must be equal
if (this == obj) {
return true;
}
// Jos other is null, must be false
if (obj == null) {
return false;
}
// If other is not Point, must be false
if (obj.getClass() != Point.class) {
return false;
}
// OTHERWISE IF
// 1 not the same object OR
// 2 not null -> good OR
// 3 not a Point class
// -> Cast the input 'obj' as a Point object
Point other = (Point) obj;
//THEN CHECK
// If x and y are equal, points are equal
return (x == other.x && y == other.y);
}
}
The implementation of the method (usually) follows the same structure.
Note that it's up to the programmer to decide when two objects should be equal: do ALL ATTRIBUTES need to be EQUAL OR ONLY SOME?
For example, we can decide that 2 Student objects are equal if they have
1 - the 'same student id' - as the rest of the attributes are not important
2 - (but then again, in some other case we may require that 'all attributes' have equal value for 'students' to be equal):
class Student extends Person {
// Name and email are inherited from Person
private String studentId;
private int credits;
public Student(String studentId, String name, String email, int credits) {
super(name, email);
this.studentId = studentId;
this.credits = credits;
}
@Override
public boolean equals(Object obj) {
// SAME OBJECCT
if (this == obj) {
return true;
}
// NOT NULL
if (obj == null) {
return false;
}
// not 'Student' class
if (obj.getClass() != Student.class) {
return false;
}
// SAME studentId
Student other = (Student) obj;
// Strings are compared with equals method
return studentId.equals(other.studentId);
}
}
A typical error is to forget to use the 'equals' method when comparing objects:
for example, String objects' equality must be checked with equals method instead of == operator.
Most editors provide a way to insert the equals method automatically,
plese refer to your editor's documentation (or google it - for example "visual studio code java equals".
|