I've been recently converting some legacy code to use Generics and ive been running into problems. Below is an example of one wall ive run into. A ClassCastException is throw where new Employee Ojects are added to the Set. I understand why but i can't figure out a work around using Wildcards. Does anyone have any suggestions? Perhaps i should use Generics instead? Thanks.
Code:import java.util.*; class Person{ public String fname; private String lname; public Person(String fname, String lname){ this.fname = fname; this.lname = lname; } } class Employee extends Person{ private String dept; private String empid; public Employee(String dept, String empid, String fname, String lname){ super(fname,lname); this.dept = dept; this.empid = empid; } } class Aux{ public static void listEmployee(Collection<? extends Person> person){ for(Person p: person){ System.out.print(p.fname); } } } public class Directory{ public static void main(String[] args){ Set<Employee> directory = new TreeSet<Employee>(); directory.add(new Employee("Shipping","9878","Bill","Gates")); directory.add(new Employee("Mailroom","6546","John","Holmes")); Aux.listEmployee(directory); } }




Reply With Quote