How to initialize a generic variable

Viewed 196

I'm having trouble working with generics. I have a class as

public class findMinMax<T extends Comparable <T>> {
  
   private T min; 
   private T max;
   
   public findMinMax() {
     //Need to initialize min max to something so that I can compare them
   }
    
   public void find(T value) {
      if (min == null || min.compareTo(value) > 0) 
         min = value;
      if (max == null ||value.compareTo(max) > 0)
         max = value;
   }
}

So how can you initialize a generic variable? Thanks

3 Answers

You can initialize them to null (actually they will be null by default, so no need to explicitly initialize them), but then you'll need to add null checks in your find method:

public class findMinMax<T extends Comparable <T>> {
  
   private T min; 
   private T max;
   
   public findMinMax() {
   }
    
   public void find(T value) {
      if (min == null || min.compareTo(value) > 0) 
         min = value;
      if (max == null || value.compareTo(max) > 0)
         max = value;
   }
}

The generic information is only used at compile time. The 'T' and its meaning has disappeared in compiled (and running) code.

But you can pass the class by constructor, and create an instance in a generic way:

public class findMinMax<T extends Comparable <T>> {

   private T value;
   private T min;
   private T max;

   public findMinMax(Class<T> aClass)
   {
       value = aClass.newInstance();
       min = aClass.newInstance();
       max = aClass.newInstance();
   }

   ....
}

The concrete class T needs a parameterless constructor.

Comparable is null-friendly. But your code is not.

If you want to make your code null-friendly, use this:

public class FindMinMax<T extends Comparable <T>> {
  
   private T min; 
   private T max;
   private boolean firstCall = true;
   
   public void find(T value) {
      if (firstCall) {
        min = value;
        max = value;
        firstCall = false;
      } else if (value != null) {
        if (value.compareTo(min) < 0) {
          min = value;
        }
        if (value.compareTo(max) > 0) {
          max = value;
        }
      } else {
        if (min != null && min.compareTo(value) > 0) {
          min = value;
        }
        if (max != null && max.compareTo(value) < 0) {
          max = value;
        }
      }
   }
}
Related