Java Reference
In-Depth Information
}
Directory "TryParameterizedMethods"
Although you have used the same identifier,
E
, as the type parameter, it has nothing to do with the
E
that
you used as the parameter for the previous version of
add()
. The scope of a type parameter for a method is
the method itself, so the two
E
s are quite separate and independent of one another. You could use
K
or some
other parameter name here if you want to make it absolutely obvious. Let's give it a whirl.
TRY IT OUT: Using Parameterized Methods
First, create a directory to hold the source files for this example and copy the files containing the
Person
and
Manager
class definitions to it. You also need the
BinaryTree.java
file containing the version with
the parameterized
add()
methods and the source file for the
LinkedList<>
generic type. Here's the pro-
gram to make use of these:
public class TryParameterizedMethods {
public static void main(String[] args) {
BinaryTree<Person> people = new BinaryTree<>();
// Create and add some Manager objects
Manager[] managers = { new Manager("Jane",1), new
Manager("Joe",3),
new
Manager("Freda",3)};
for(Manager manager : managers){
people.add(manager);
}
// Create and add some Person objects
Person[] persons = {
new Person("Will"), new Person("Ann"), new
Person("Mary"),
new Person("Tina"), new Person("Stan")};
for(Person person : persons) {
people.add(person);
}
listAll(people.sort()); // List the sorted contents of the tree
}
// Parameterized method to list the elements in any linked list
public static <T> void listAll(LinkedList<T> list) {
for(T obj : list) {
System.out.println(obj);
}