Results 1 to 7 of 7

Thread: Generic methods or Wildcard types?{Resolved}

Threaded View

  1. #1

    Thread Starter
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418

    Resolved Generic methods or Wildcard types?{Resolved}

    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);
      }
     }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width