java compareTo 和 binarySearch

来源:互联网 发布:虚拟炒股软件 编辑:程序博客网 时间:2024/05/17 17:16

1.compareTo( ) 函数

两个维度的compareTo 方法如下写:

 public  int  compareTo(WordProperty o) {            long diff = this. cityId - o. cityId;            diff = ( diff == 0) ? this. typeScore - o. typeScore : diff; //谁调用compareTo() 就是谁和括号中的比, a.compareTo(b) 得-1,说明a 和b 比,比小了            return diff > 0 ? 1 : ( diff == 0 ? 0 : -1);     }
以上这个compareTo 是先和 java jdk  中Integer 类的compareto 相同,Integer 类1020 行如下:

 public int compareTo(Integer anotherInteger) {        return compare(this.value, anotherInteger.value );    }    public static int compare (int x , int y ) {        return (x < y) ? -1 : ((x == y) ? 0 : 1);//    }
意思是如果compareTo( ) 得数是-1,则不换位置,为1,则换位置,经过比较 / 换位之后,各个Integer 放在 List 中,有序,即为sort  的结果:   [1,2,3,3,3,5]

2. Collections. binarySearch( list, 4) 函数

[1,3,3,3,3,5]  查找4,返回  -6        [1,3,3,3,5] 查找2,返回-2
Collections 类 286 行源码如下:

int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key)    {        int low = 0;        int high = list.size()-1;        ListIterator<? extends Comparable<? super T>> i = list.listIterator();        while (low <= high) {            int mid = ( low + high) >>> 1;            Comparable<? super T> midVal = get(i , mid );            int cmp = midVal.compareTo( key);            if ( cmp < 0)                low = mid + 1;            else if ( cmp > 0)                high = mid - 1;            else                return mid; // key found        }        return -(low + 1);  // key not found    }
故找不到的时候,返回的是这个数最应该插入到哪个位置(即数字插入后,他的位置中的元素顺次后移,能重新有序),再加个负号。

之所以加 1 ,是因为数组下标比真实的数组中的数字位置小 1








0 0
原创粉丝点击