A
DEMONSTRATION OF = = , equals, and compareTo
A CLASS CALLED “Car” defined to use the Comparable interface with
a compareTo definition.
public class Car implements Comparable{
String owner;
String color;
Car(String
own, String c) {
owner
= own;
color
= c;
}
public
String getOwner() {
return
owner;
}
public
String getColor() {
return
color;
}
// YOU MUST CREATE AN IMPLEMENTATION
FOR THE ABSTRACT METHOD compareTo from the
// Comparable interface
public
int compareTo(Object otherObject)
{
//otherObject
is passed in as an Object type so let’s convert it into
//a Car
type object.
Car otherCar = (Car)otherObject;
int retValue;
if
(owner.equals(otherCar.owner))
{
retValue = 0;
}
else
{
retValue = -1;
}
return
retValue;
}
}
A Class called
MAKECAR that will demonstrate the use of the equals techniques
// Work with == equals and compareTo
public class MakeCars{
public
static void main(String[] args) {
Car car1 = new Car("Dan", "blue");
Car car2 = new Car("Dan", "blue");
Car car3 = car2;
// THE OBJECTS WILL NOT
BE EQUAL DON'T USE == WITH STRINGS/
OBJECTS
if
(car1 == car2)
System.out.println("car1
and car2 are ==");
else
System.out.println("car1
and car2 are not ==");
// WHILE THE OBJECTS
CONTAIN THE SAME VALUES, THEY ARE NOT COMPLETELY EQUAL
if
(car1.equals(car2))
System.out.println("car1
and car2 are equals");
else
System.out.println("car1
and car2 are NOT equals");
// car3 is a reference to
car2, so they are equal
if
(car2.equals(car3))
System.out.println("car2
& car3 : The objects are equals");
else
System.out.println("car2
& car3 : The objects are NOT equals");
// compareTo - using definition from Cars Class (compareTo)
int x = car1.compareTo(car2);
if
(x == 0)
System.out.println("car1
& car2 compareTo results in equals");
else
System.out.println("car1
& car2 compareTo results in NOt
equals");
x = car2.compareTo(car3);
if
(x == 0)
System.out.println("car2
& car3 : The compareTo are equals");
else
System.out.println("car2
& car3 : The compareTo are NOT equals");
System.out.println(car1 +
" " + car2);
System.out.println(car2 +
" " + car3);
}
}
Things to Try:
1.
Run the MakeCar Class and investigate the printout.
2.
Try changing
the name of owner in Class 2 to “Danny”
3.
Rewrite the compareTo method to test the color instead of owner.
4.
Try altering
the color of one of the Objects.
5.
Summarize
your findings.