Java Reference
In-Depth Information
You can override the equals method in the Circle class to compare whether two circles
are equal based on their radius as follows:
public boolean equals(Object o) {
if (o instanceof Circle) {
return radius == ((Circle)o).radius;
}
else
return false ;
}
Note
The == comparison operator is used for comparing two primitive data type values or for
determining whether two objects have the same references. The equals method is
intended to test whether two objects have the same contents, provided that the method
is overridden in the defining class of the objects. The == operator is stronger than the
equals method, in that the == operator checks whether the two reference variables
refer to the same object.
==
vs. equals
Caution
Using the signature equals(SomeClassName obj) (e.g., equals(Circle c))
to override the equals method in a subclass is a common mistake. You should use
equals(Object obj ). See CheckPoint Question 11.28.
equals(Object)
11.27
Does every object have a toString method and an equals method? Where do they
come from? How are they used? Is it appropriate to override these methods?
Check
Point
11.28
When overriding the equals method, a common mistake is mistyping its signature in
the subclass. For example, the equals method is incorrectly written as
equals(Circle circle) , as shown in (a) in following the code; instead, it should
be equals(Object circle) , as shown in (b). Show the output of running class
Test with the Circle class in (a) and in (b), respectively.
public class Test {
public static void main(String[] args) {
Object circle1 = new Circle();
Object circle2 = new Circle();
System.out.println(circle1.equals(circle2));
}
}
class Circle {
double radius;
class Circle {
double radius;
public boolean equals( ) {
return this .radius == circle.radius;
Circle circle
public boolean equals(
Object circle
) {
return this .radius ==
((Circle)circle).radius;
}
}
}
}
(a)
(b)
11.11 The ArrayList Class
An ArrayList object can be used to store a list of objects.
Key
Point
VideoNote
Now we are ready to introduce a very useful class for storing objects. You can create an array
to store objects. But, once the array is created, its size is fixed. Java provides the ArrayList
The ArrayList class
 
 
Search WWH ::




Custom Search