Arrays.sort(a) 自定义排序

 Arrays.sort(a) 自定义排序,(需实现接口:Comparable)

package com.hd;

import java.util.Arrays;

class Person implements Comparable{
    int id ;
    int score ;
    public Person(int id,int score){
        this.id = id;
        this.score = score ;
    }
    @Override
    public String toString(){
        return "id:"+id+" score:"+score ;
    }
    
    @Override
    public int compareTo(Object o) {
        Person p = (Person)o ;
        int temp ;
     temp= this.score > p.score ? 1:this.score==p.score?0:-1;
        if(temp==0)
            return this.id >p.id? 1:-1;
        return temp ;
    }

}
public class Main
{
    public static void main(String args[])
    { 
        Person p[]={new Person(9,80),
            new Person(8,90),
            new Person(8,70)};
        Arrays.sort(p);
        System.out.println(Arrays.toString(p));
        
    }
}
//---------[id:8 score:70, id:9 score:80, id:8 score:90]
    

 



 1. sort():


Arrays.sort(Object[] a) --> Arrays.mergeSort()
--->((Comparable) dest[j-1]).compareTo(dest[j])>0
Comparable转换是为了调用compareTo()
      虽不在编译的时候报错,但如果没实现的话,
      运行时会:ClassCastException*,



 2. toString():


Arrays.toString(Object[] a)
          let the string of array append :[ .... ]
---->include:String.valueOf(Object a)
----->include:Object.toString()
--< self implement
        (overwrite the method of super class,Object)
          impelment person.toString();


 3. 导包:


     为什么在Arrays中可以未经导包,自由出现Comparable接口,
java.lang包是核心类库,它包含了运行java程序必不可少的系统类,
     系统自动为程序引入java.lang包中的类
    (如:System Math String)因此不需要再import引入;

-----------------------------------------------
   4.继承:


  (1)构造:
   子类的构造方法在创建一个子类的对象时,总是先调用父类的某个构造方法,
     如无指出,则是无参数的那个;
   因此,在子类创建对象时,不仅子类中声明的成员变量被分配了内存,
     而且父类中的成员变量也被分配了内存,
   看似浪费 ,但是注意,子类中还有一部分中的方法时从父类继承的
     这部分方法却可以操作这部分未继承的private成员;

 (2)重写类型
    jdk1.5后,允许重写方法的类型可以是父类方法的子类型,即不必完全一致,
     也就是说如果父类方法中的类型是类,则重写方法中可以是子类,

 (3)上转型
    对象的上转型对象:(前提是 B extends A )
    A a ;
    a = new B() ;
    但是上转型对象会失去原对象的一些属性,
    1,。不能操作子类新增的属性;
    2. 继承的或重写的,
    因为在Object 中没有实现,



 5.接口:
    不能自己new对象,
    只能得到所实现的类的引用,然后使用所实现的方法,接口回调;


 

posted @ 2013-11-09 14:39  寻影  阅读(591)  评论(0编辑  收藏  举报