java 实现compare接口_java 常用接口的实现--compareable

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

//interface declaration:

/**

* This interface should be implemented by all classes that wish to define a

* natural order 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.

*

* 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).

*

* 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 {

/**

* 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

{

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;

}

}

//上面便是实现的例子

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值