java 常用接口的实现compareable

//主要用于实现比较的接口 用于对象的比较大小 排序等操作

 //interface declaration:

/**
 * This interface should be implemented by all classes that wish to define a
 * <em>natural order</em> of their instances.
 * mailto:%7B@link java.util.Collections#sort} and mailto:%7B@code java.util.Arrays#sort} can then
 * be used to automatically sort lists of classes that implement this interface.
 * <p>
 * The order rule must be both transitive (if mailto:%7B@code x.compareTo(y) < 0} and
 * mailto:%7B@code y.compareTo(z) < 0}, then mailto:%7B@code x.compareTo(z) < 0} must hold) and
 * invertible (the sign of the result of x.compareTo(y) must be equal to the
 * negation of the sign of the result of y.compareTo(x) for all combinations of
 * x and y).
 * <p>
 * In addition, it is recommended (but not required) that if and only if the
 * result of x.compareTo(y) is zero, then the result of x.equals(y) should be
 * mailto:%7B@code true}.
 */
public interface Comparable<T> {

    /**
     * Compares this object to the specified object to determine their relative
     * order.
     *
     * @param another
     *            the object to compare to this instance.
     * @return a negative integer if this instance is less than mailto:%7B@code another};
     *         a positive integer if this instance is greater than
     *         mailto:%7B@code another}; 0 if this instance has the same order as
     *         mailto:%7B@code another}.
     * @throws ClassCastException
     *             if mailto:%7B@code another} cannot be converted into something
     *             comparable to mailto:%7B@code this} instance.
     */
    int compareTo(T another);
}

//for example:

public class HighScore implements Comparable<HighScore>
{
 private String myDate;
 private int myGameType;
 private int myLevel;
 
 public HighScore(String date, int gameType, int level)
 {
  myDate = date;
  myGameType = gameType;
  myLevel = level;
 }
 
 @Override
 public int compareTo(HighScore other)
 {
  if(this.getGameType()==other.getGameType())
  {
   if(this.getLevel()==other.getLevel())
   {
    return 0;
   }
   else if(this.getLevel()>other.getLevel())
   {
    return -1;
   }
   else
   {
    return 1;
   }
  }
  else
  {
   if(this.getGameType()>other.getGameType())
   {
    return -1;
   }
   else
   {
    return 1;
   }
  }
 }
 
 @Override
 public String toString()
 {
  return myDate+";"+myGameType+";"+myLevel;
 }

 //*********GETTERS*************/
 public String getDate()
 {
  return myDate;
 }

 public int getGameType()
 {
  return myGameType;
 }
 
 public int getLevel()
 {
  return myLevel;
 }
}


//上面便是实现的例子 

原文地址:https://www.cnblogs.com/fwycmengsoft/p/2248002.html