|
Optimizing Web Services Using Java, Part I by Jordan Anastasiade
WSJ Vol 03 Issue 12 - pg.51
Listing 1: Web service implementation – generates runtime error
Object[] objectArray = new Integer[1];
objectArray[0] = "zero"; //throws exception at run-time
Listing 2: Company class hierarchy implementation
public abstract class Employee {
public abstract int salaryFrom(Company c);
}
public class Sales extends Employee {
...
public int salaryFrom(Company c){ ...}
...
}
public class Programmer extends Employee {
...
public int salaryFrom(Company c){ ...}
...
}
public class Student extends Employee {
private List<CoopStudent> coopStudents;
public int salaryFrom(Company c){ ...}
...
}
public class Company {
int salary = 0;
public void daySalary(Employee e) {
salary += e.salaryFrom(this);
}
}
Listing 3: Department salary web service implementation
public void
departmentSalary(List<Employee> employees) {
for (Employee e: employees)
salary += e.salaryFrom(this);
}
Listing 4: Error writing to a covariant type
List<Student> students =
new LinkedList<Student>();
List<? extends Employee> employees = students;
employees.add(0, new GeneralManager()); // error
Listing 5: Using covariant generic type as factory
public class HummanResources {
private Factory<? extends Employee> factory;
public void
setFactory(Factory<? extends Employee> f) {
factory = f;
}
/* Generates a new employee object */
public void newEmployee() {
Employee e = factory.create();
...
}
}
Listing 6: Using covariant and contravariant generic type
void move(List<? super Employee> to,
List<? extends Employee> from);
Listing 7: Using contravariant generic type as comparator
public interface Comparator<T> {
int compare(T x, T y);
}
public static <T>
T theBest(List<T> e, Comparator<? super T> c);
Listing 8: Using bivariant generic type
public int
all(List<? extends List<?>> departments) {
int total = 0;
for (List<?> department : departments) {
total += department.size();
}
return total;
}
|