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/archive/2011/11/14/2248002.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值