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
總結
以上是生活随笔為你收集整理的java 常用接口的实现--compareable的全部內容,希望文章能夠幫你解決所遇到的問題。

- 上一篇: MDA:模型驱动架构 简介
- 下一篇: wcf系列---- binding的使用