Daniel Thayne
Daniel Thayne

Reputation: 7

Properly implementing comparable and generics

I am struggling to understand how to implement generics and comparable into my code. I am tasked with converting the method below to proper generic methods. I also need to switch out the parameters with proper generics.

public static String min(String a, String b) {
    if (a < b)
         return a;
    else
         return b;
}
    
public static String max(String a, String b) {
    if (a < b)
         return b;
    else
         return a;
}

And this is my attempt

public static <AnyType> min(<AnyType> a, <AnyType> b) {
    if (a < b)
         return a;
    else
         return b;
}
    
public static <AnyType> max(<AnyType> a, <AnyType> b) {
    if (a < b)
         return b;
    else
         return a;
}

Upvotes: 0

Views: 80

Answers (2)

Old Dog Programmer
Old Dog Programmer

Reputation: 1251

You are not going to be able to write a single compareTo method that will work for any type. But, you can write a min and max that will work on any type that properly implements Comparable.

Comparable is a Java interface. It has a method compareTo, which contains no code. Using it requires a compareTo method be implemented for each class that uses it.

Use of the Comparable interface looks something like this:

 public class Foo implements Comparable<Foo> { 

That requires, somewhere in class Foo, this:

     public int compareTo (Foo someFoo) { ... }

Where ... is replaced by code specific to Foo.

Then, a class that needs to compare two variables of type Foo might have code like this:

  Foo bar = new Foo();
  Foo bin = new Foo();
  ...
  if (bar.compareTo(bin) < 0) { ...

If there were another class that implements Comparable, that class would also need a compareTo method specific to that class.

You could write generic min and max methods that would work on several classes, as long as those classes implement Comparable. The <T extends Comparable<T>> enforces that.

public static <T extends Comparable<T>> T min (T a, T b) {
    if (a.compareTo(b) <= 0) return a;
    return b;
}
public static <T extends Comparable<T>> T max (T a, T b) {
    if (a.compareTo(b) >= 0) return a;
    return b;
}

However, generics are not necessary in this case. Java allows the name of an interface to be used as a type:

public static Comparable min (Comparable a, Comparable b) {
    if (a.compareTo(b) <= 0) return a;
    return b;
}
public static Comparable max (Comparable a, Comparable b) {
    if (a.compareTo(b) >= 0) return a;
    return b;
}

Upvotes: 1

モキャデ
モキャデ

Reputation: 385

You have to ensure that AnyType is comparable.

public static <AnyType extends Comparable<AnyType>> AnyType min(AnyType a, AnyType b) {
    return a.compareTo(b) < 0 ? a : b;
}

public static <AnyType extends Comparable<AnyType>> AnyType max(AnyType a, AnyType b) {
    return a.compareTo(b) > 0 ? a : b;
}

Upvotes: 2

Related Questions