1
public class Pair<F,S> implements Comparable<Pair<F,S>> {
public F first;
public S second;

public F first() {
return first;
 }

public void setFirst(F first) {
this.first=first;
 }

 public S second() {
 return second;
 }

 public void setSecond(S second) {
 this.second=second;
  }

 public Pair(F first, S second) {
 super();
  this.first=first;
   this.second=second;
  }  

 public int hashCode() {
  return(first.hashCode()^second.hashCode());
}

  @Override
 public boolean equals(Object obj) {   
 return obj instanceof Pair && ((Pair)obj).first.equals(first) &&      (Pair)obj).second.equals(second);
   }

  public String toString() {
  return first + " / " + second;
   }

  @SuppressWarnings("unchecked")
  public int compareTo(Pair<F, S> o) throws ClassCastException{

int firstCompared = ((Comparable<F>) first).compareTo(o.first());
if(firstCompared!=0) return(firstCompared);
return(((Comparable<S>)second).compareTo(o.second()));
      }

    }

and and I have the following class:

  public class Point{

public int x;
public int y;

Point(int x, int y){
    this.x = x;
    this.y = y;

}

public String toString(){

    return "(" + x + "," + y + ")";
  }
}

My Question: Suppose i have four points p1, p2, p3, p3. How can i use the Pair class to compare the pair (p1, p2) with (p2,p3)? How can i use the compareTo function? Thank you

bib
  • 944
  • 3
  • 15
  • 32

1 Answers1

5

You can't use this since your Point class does not implement Comparable<Point>. You must fix this first. And in fact, you should constrain your F and S to only classes that implement Comparable.


To constrain F and S, change class declaration to:

public class Pair<F extends Comparable<F>, S extends Comparable<S>> implements Comparable<Pair<F,S>> {

With that, you no longer have to cast in compareTo:

@Override
public int compareTo(Pair<F, S> that) {
    int cmp = this.first.compareTo(that.first);
    if (cmp == 0)
        cmp = this.second.compareTo(that.second);
    return cmp;
}

When writing code below, the compiler will tell you that Point must implement Comparable<Point>.

Once you do that, you can:

Pair<Point, Point> pair1 = new Pair<>(p1, p2);
Pair<Point, Point> pair2 = new Pair<>(p3, p4);
int cmp = pair1.compareTo(pair2);
Andreas
  • 154,647
  • 11
  • 152
  • 247
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 1
    Suggestion: You should show how to do the constraint, to help people that are not fluent in generics. – Andreas Sep 18 '15 at 22:36
  • @Andreas: I'm pressed for time, which is why I posted an incomplete answer but made it a community wiki (I get no credit for the up-votes). Please feel free to improve it if you can. Thanks! – Hovercraft Full Of Eels Sep 18 '15 at 22:37