Java Reference
In-Depth Information
}
}
Directory "TryParameterizedConstructor"
The output is
Manager Ann level: 2
Manager Ann level: 2
Manager Bert level: 2
Manager Dave level: 2
Manager Freda level: 3
Manager Jane level: 1
Manager Joe level: 3
Mary
Stan
Tina
Will
How It Works
After you create an array of Manager objects you create a BinaryTree<Person> object with the contents
of the managers array as the initial contents of the binary tree:
BinaryTree<Person> people = new BinaryTree<>(managers);
Because the constructor has an independent parameter and that parameter has the type variable for the
BinaryTree<> type as its upper bound, the constructor accepts the managers array as the argument be-
cause it is a subclass of Person , the type argument that you use to specify the type of the binary tree
object.
You then add the non-management personnel to the tree as you did in the previous example.
The output shows that the array elements were added to the binary tree and were successfully extracted
and stored in sequence in a linked list by the sort() method. However, there's something wrong with
the output. There is Ann the manager and Ann the lowly worker, and somehow in the output there are
two managers called Ann and Ann the non-manager has disappeared. The problem is the compareTo()
method in the Person class compares Person objects without reference to their position in the company
that is reflected in their class type. A non-manager is the equal of a manager and this cannot be right. You
can fix this by changing the compareTo() method definition in the Person class to the following:
public int compareTo(Person person) {
if( person == this) {
return 0;
}
if(this.getClass().getName().equals(person.getClass().getName()))
{
Search WWH ::




Custom Search