jmina
jmina

Reputation: 3

Method in generic class does not return type specified. Why?

The calls to getHighest() and getLowest() below return objects of type Comparable and not T, which is what is wanted. Why, and how can I improve this code so these calls return T instead (so that T's fields and methods are available)?

public class HighestLowest<T extends Comparable<T> >  {
  
  private T lowest;
  private T highest;
  
  public static void main(String[] args) {

    HighestLowest city;
    HighestLowest employee;
    
    City[] cities = new City[3];
    Employee[] employees = new Employee[3];

    city = new HighestLowest<City>(cities);
    employee = new HighestLowest<Employee>(employees);

The very next line generates a compiler error:

Error: cannot find symbol symbol: method getName() location: interface java.lang.Comparable

I'd like employee.getHighest() to return an Employee (rather than just a Comparable) while still using the generic class/method mechanism, but how?

    System.out.println("The oldest employee is: " +
                       employee.getHighest());

  }
  
  public T getLowest() {
    return lowest;
  }
  
  public T getHighest() {
    return highest;
  }
  
  public HighestLowest(T[] of) {
    lowest = lowest(of);
    highest = highest(of);
  }
  
  private T lowest(T[] of) {
    
    T lowest = of[0];
    
    for (T element : of) {
      if (element.compareTo(lowest) < 0) {
        lowest = element;
      }
    }
    
    return lowest;
    
  }
  
  private T highest(T[] of) {
    
    T highest = of[0];
    
    for(T element : of) {
      if (element.compareTo(highest) > 0) {
        highest = element;
      }
    }
    
    return highest;
    
  }
  
}

  class Employee implements Comparable<Employee> {
    // ...
  }
  
  class City implements Comparable<City> {
    // ...
  }

Upvotes: 0

Views: 41

Answers (1)

Your employee variable is declared as raw type HighestLowest. The compiler then knows only about its bound which is Comparable. Compiler does not know you assigned generic type in runtime.

Solution: declare it as generic type HighestLowest<Employee>. The same situation is with city. With Java 7+, you can omit repeating generic argument and use employee = new HighestLowest<>(employees); (the so called diamond operator)

Upvotes: 3

Related Questions