Java Data Structures - Contents
A D V E R T I S E M E N T
Comparing Objects in Java can be a daunting task,
especially if you have no idea how it's done. In Java, we can only compare variables of native
type. These include all but the objects (ex: int , float , double ,
etc.). To compare Objects, we have to make objects with certain properties; properties
that will allow us to compare.
We usually create an interface , and implement
it inside the objects we'd like to compare. In our case, we'll call the interface
pComparable . Interfaces are easy to write, since they're kind of like abstract
classes.
public interface pComparable{
public int compareTo(Object o);
}
As you can see, there is nothing special to simple
interfaces. Now, the trick is to implement it. You might be saying, why am I
covering comparing of objects right in the middle of a binary tree discussion... well, we
can't have a binary search tree without being able to compare objects. For example, if
we'd like to use integers in our binary search tree, we'll have to design our own integer,
and let it have a pComparable interface.
Next follows our implementation of pInteger ,
a number with a pComparable interface . I couldn't just extend
the java.lang.Integer , since it's final (cannot be extended )
(those geniuses!).
public class pInteger implements pComparable{
int i;
public pInteger(){
}
public pInteger(int j){
set(j);
}
public int get(){
return i;
}
public void set(int j){
i = j;
}
public String toString(){
return ""+get();
}
public int compareTo(Object o){
if(o instanceof pInteger)
if(get() > ((pInteger)o).get())
return 1;
else if(get() < ((pInteger)o).get())
return -1;
return 0;
}
}
I believe most of the interface is self
explanatory, except maybe for the compareTo(Object) method. In the method, we
first make sure that the parameter is of type pInteger , and later using
casting, and calling methods, we compare the underlying native members of pInteger
and return an appropriate result.
A note on JDK 1.2: In the new versions of the JDK,
you won't need to implement your own pComparable , or your own pInteger ;
since it's built in! There is a Comparable interface , and it's already implemented
by the built in java.lang.Integer , java.lang.String , and other
classes where you might need comparisons. I'm doing it this way only for compatibility
with the older versions of JDK. I'll talk about JDK 1.2 features later in this document
(hopefully).
Back to Table of Contents
A D V E R T I S E M E N T
|
Subscribe to SourceCodesWorld - Techies Talk |
|