1. 程式人生 > 實用技巧 >常用類學習

常用類學習

常用類

Object類

超類、基類,所有累得直接或者間接弗雷,位於繼承樹的最頂層

任何類,如果沒有書寫extends繼承某個類,都預設直接繼承Object類,否則為間接繼承

Object類中所定義的方法,是所有物件都具備的方法

Object型別可以存出任何物件:作為引數,可接受任何物件;作為返回值,可返回任何物件。

getClass()方法

返回引用中儲存的實際物件型別

應用:常用於判斷兩個引用中實際儲存物件型別是否一致

hashCode()方法

返回該物件的雜湊值

雜湊值是根據物件的地址或字串或數字使用hash演算法計算出來的int型別的數值

一般情況下,相同的物件返回相同的雜湊值(判斷兩個物件是不是同一個)

toString()方法

返回該物件的字串表示(表現形式)

可以根據程式的需求覆蓋這個方法,如:展示物件的各個屬性值

public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

equals()方法

比較兩個物件地址是否相同

可以進行覆蓋,比較兩個物件的內容是否相同

重寫的思想:

  1. 判斷兩個物件是否為同一引用,同一引用說明內容相同
  2. 判斷和其對比的內容是不是空值,如果是空,則不存在相同比較
  3. 判斷兩者是否為相同型別(由於比較的物件為最底層的子類,所以用instanceof)
  4. 強制型別轉換

finalize()方法

當物件被判定為垃圾物件的時候,由JVM自動改呼叫此方法,用以標記垃圾物件,進入回收佇列

垃圾物件:沒有有效引用指向此物件時,為垃圾物件

垃圾回收:由GC銷燬垃圾物件,釋放資料儲存空間

自動回收機制:JVM的記憶體耗盡,一次性回收所有垃圾物件

手動回收機制:使用System.gc();通知JVM執行垃圾回收

程式碼例項

public class GraduateStudent {
    private String name;
    private int age;
    public GraduateStudent(){}

    public GraduateStudent(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return name+":"+age+" years old";
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj){
            return true;
        }
        if (obj == null){
            return false;
        }
        if(obj instanceof GraduateStudent){
            GraduateStudent gs = (GraduateStudent)obj;
            if (this.name.equals(gs.getName())&&this.age==gs.getAge()){
                return true;
            }else {
                return false;
            }
        }
        return false;
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println(this.name+"物件被回收了");

    }
}
public class Application {
    public static void main(String[] args) {
        GraduateStudent gs1 = new GraduateStudent("wyb",23);
        GraduateStudent gs2 = new GraduateStudent("wyf",24);
        GraduateStudent gs3 = new GraduateStudent("wyb",23);
        //判斷gs1 gs2是不是一個型別
        Class class1 = gs1.getClass();
        Class class2 = gs2.getClass();
        Class class3 = gs3.getClass();
        if (class1 == class2){
            System.out.println("The class of the gs1 is same to the gs2.");
        }else{
            System.out.println("The class of the gs1 is different from the gs2.");
        }
        if (class1 == class3){
            System.out.println("The class of the gs1 is same to the gs3.");
        }else{
            System.out.println("The class of the gs1 is different from the gs3.");
        }
        System.out.println("==================hashCode方法=================");
        //hashCode方法
        System.out.println(gs1.hashCode());
        System.out.println(gs2.hashCode());
        System.out.println(gs3.hashCode());
        GraduateStudent gs4 = gs1;
        System.out.println(gs4.hashCode());
        System.out.println("==================toString方法(練習重寫)=================");
        //toString方法
        System.out.println(gs1.toString());
        System.out.println(gs3.toString());
        System.out.println("==================equals方法(練習重寫)=================");
        //equals方法
        System.out.println(gs1.equals(gs3));
        System.out.println("==================finalize方法(練習重寫)=================");
        //finalize方法
        GraduateStudent gs5 = new GraduateStudent("aaa",30);
        GraduateStudent gs6 = new GraduateStudent("bbb",30);
        new GraduateStudent("ccc",30);
        new GraduateStudent("ddd",30);
        GraduateStudent gs9 = new GraduateStudent("eee",30);
        //回收垃圾
        System.gc();
        System.out.println("回收垃圾");

    }
}

包裝類

基本資料型別所對應的引用資料型別(基本資料型別只能用基本運算子操作運算,為了擴充套件功能而出現了包裝類)

把基本型別的資料放進堆裡

Object可統一所有資料,包裝類的預設值是null

基本資料型別 包裝型別
byte Byte
short Short
int Integer
float Float
boolean Boolean
char Character
double Double
long Long

型別轉換與裝箱、拆箱

基本型別=====>引用型別(裝箱)

基本型別<=====引用型別(拆箱)

8種包裝類提供不同型別之間的轉換方式

  1. Number父類中提供的六個共性方法
  2. parseXXX()靜態方法
  3. valueOf()靜態方法

注意:要保證型別相容,否則會丟擲NumberFormatException異常

程式碼例項

public class Demo01 {
    public static void main(String[] args) {
        //裝箱操作 基本型別=====>引用型別
        int num1 = 18;
        Integer integer1 = new Integer(num1);
        Integer integer2 = Integer.valueOf(num1);
        //拆箱操作 基本型別<=====引用型別
        Integer integer3 = new Integer(10);
        int num2 = integer3.intValue();
        System.out.println("裝箱");
        System.out.println(integer1);
        System.out.println(integer2);
        System.out.println("拆箱");
        System.out.println(num2);

        //JDK1.5之後提供了自動裝箱和開箱
        int age =30;
        //自動裝箱
        System.out.println("自動裝箱");
        Integer integer4 = age;
        System.out.println(integer4);
        //自動拆箱
        System.out.println("自動拆箱");
        int age2 = integer4;
        System.out.println(age2);

        //基本型別和字串之間的轉換
        System.out.println("===============基本型別和字串之間的轉換===============");
        System.out.println("基本型別====>字串");
        int num3 = 11927050;
        String s1 = num3+"";//使用+號
        String s2 = Integer.toString(num3);//使用toString方法
        String s3 = Integer.toString(num3,16);//使用toString方法,後面表示進位制
        System.out.println(s3);
        System.out.println("基本型別<====字串");
        String s4 = "11927050";
        int num4 = Integer.parseInt(s4);
        System.out.println(num4);

        //boolean字串轉換成基本型別,只有"true"會轉換成true,其他的都會變成false
        String s5 = "true";
        String s6 = "amazing";
        boolean b1 = Boolean.parseBoolean(s5);
        boolean b2 = Boolean.parseBoolean(s6);
        System.out.println(b1);
        System.out.println(b2);
       
    }
}

整數緩衝區

Java預創了256個常用的整數包裝型別物件(-128~127)

在實際應用中,對已建立的物件進行復用(節省記憶體消耗)

程式碼例項

public class Demo02 {
    public static void main(String[] args) {
        //interview question
        Integer integer1 = new Integer(100);
        Integer integer2 = new Integer(100);
        System.out.println(integer1==integer2);

        Integer integer3 = Integer.valueOf(100);
        Integer integer4 = Integer.valueOf(100);
        System.out.println(integer3==integer4);//true

        Integer integer5 = Integer.valueOf(128);
        Integer integer6 = Integer.valueOf(128);
        System.out.println(integer5==integer6);//false
    }
}

String類

字串是常量,建立之後不能改變。

字串字面值儲存在字串池中,可以共享。

程式碼例項

public class Demo01 {
    public static void main(String[] args) {
        String name = "Faye";//"Faye"常量儲存在字串池(常量池)中
        name = "Chile";//"Chile"賦值給name變數 沒有修改資料,而是重新開闢了一個空間。(不可變性)
        String name2 = "Chile";
        //另一種建立字串的方式
        String name3 = new String("Nikita");//浪費空間
        String name4 = new String("Nikita");
        System.out.println(name4 == name3);//比地址
        System.out.println(name3.equals(name4));//比內容
    }
}

常用方法

public class Demo02 {
    public static void main(String[] args) {
        /*字串方法的使用
        1. length()返回字串長度
        2. charAt(int index)返回某個位置的字元
        3. contains(String str)判斷是否包含某個子字串
        4. toCharArray()將字串轉換為陣列
        5. indexof()返回子字串首次出現的位置
        6. lastindexof()返回字串最後一次出現的位置
        7. trim()去掉字串前後的空格
        8. toUpperCase()把小寫變成大寫
        9. toLowerCase()把大寫變成小寫
        10. endwith() startwieh() 是否以…結尾/開始
        11. replace()用新的字串來替換舊的字串
        12. split()對字串進行拆分
        13. equals compare 比較大小

        */
        String sentence = "Faye is my favorite singer.Faye is my favorite singer.Faye is my favorite singer.";
        System.out.println(sentence.length());
        System.out.println(sentence.charAt(sentence.length()-1));
        System.out.println(sentence.contains("Faye"));
        System.out.println(Arrays.toString(sentence.toCharArray()));
        System.out.println(sentence.indexOf("e"));
        System.out.println(sentence.indexOf("e",4));//從哪個腳標開始尋找
        System.out.println(sentence.lastIndexOf("e"));
        System.out.println(sentence.replace("Faye","FaYe"));
        String[] arr = sentence.split("[ .]");
        System.out.println(arr.length);
        for (String s : arr) {
            System.out.println(s);
        }
        String s1 = "I LOVE YOU!";
        String s2 = "I love you!";
        System.out.println(s1.equals(s2));
        System.out.println(s1.equalsIgnoreCase(s2));
        String s3 = "abc";
        String s4 = "def";
        String s5 = "abcdefghijklmn";
        System.out.println(s3.compareTo(s4));
        System.out.println(s3.compareTo(s5));

    }
}

練習題

public class Demo03 {
    public static void main(String[] args) {
        String str = "this is a text";
        Arrays arrays1[];
        str.replace("text","easy practice");
        String [] arr = str.split(" ");
        for (String s : arr) {
            System.out.println(s);
        }
        for(int i = 0;i<arr.length;i++){
            char first = arr[i].charAt(0);
            char uf = Character.toUpperCase(first);
            String news = uf + arr[i].substring(1);

            System.out.println(news);
        }
    }
}

可變字串

StringBuffer:可變長字串,JDK1.0提供,執行效率慢,執行緒安全

StringBuilder:可變長字串,JDK1.5提供,執行效率快,效率不安全

區別:1. 效率比String高 2. 節省記憶體

程式碼例項

public class Demo04 {
    //StringBuffer StringBuilder
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        // append()追加內容
        sb.append("Faye");
        System.out.println(sb);
        sb.append(" is the best singer.");
        System.out.println(sb);
        // insert()新增
        sb.insert(0,"I think ");
        System.out.println(sb);
        // replace()替換
        sb.replace(0,2,"Everyone ");
        System.out.println(sb);
        // delete()刪除
        sb.delete(0,15);
        System.out.println(sb);

        StringBuilder sb2 = new StringBuilder();
    }
}
public class Demo05 {
    //驗證StringBuilder效率高於String
    public static void main(String[] args) {
        //設定開始時間
        long start = System.currentTimeMillis();
        StringBuffer sb = new StringBuffer();
        //StringBuilder sb = new StringBuilder();
        for (int i = 0;i<99999;i++){
            sb.append(i);
        }
        System.out.println(sb);
        long end = System.currentTimeMillis();
        System.out.println("time is "+(end-start));
    }
}

BigDecimal類

double和float的儲存都是近似值

BigDecimal是精確儲存,可以用於大的浮點數的精確計算

位於java.math包中

public class Demo06 {
    public static void main(String[] args) {
        double d1 = 0.9;
        double d2 = 0.8;
        System.out.println(d1-d2);
        System.out.println((d1-d2)/0.1);
        BigDecimal bd1 = new BigDecimal("1.0");
        BigDecimal bd2 = new BigDecimal("0.9");
        BigDecimal bd4 = new BigDecimal("0.05");
        BigDecimal bd5 = new BigDecimal("0.05");
        BigDecimal bd3 = bd1.subtract(bd2);
        BigDecimal bd6 = bd4.add(bd5);
        System.out.println(bd6);
        System.out.println(bd3);
        BigDecimal bd7 = new BigDecimal("1.4").subtract(new BigDecimal("0.5")).divide(new BigDecimal("0.9"));
        BigDecimal bd8 = new BigDecimal("10").divide(new BigDecimal("3"),2,BigDecimal.ROUND_HALF_UP);
        System.out.println(bd8);
    }
}

Date類

表示特定的瞬間 精確到毫秒 Date類中的大部分方法都被Calendar類中的方法取代了。

public class Demo08 {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.getTime().toLocaleString());
        System.out.println(calendar.getTimeInMillis());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);//HOUR_OF_DAY=====>24h HOUR===>12h
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        System.out.println(year+"年"+month+"月"+day+"日"+hour+":"+minute+":"+second);
        //修改時間
        Calendar calendar2 = Calendar.getInstance();
        calendar2.set(Calendar.DAY_OF_MONTH,5);
        System.out.println(calendar2.getTime().toLocaleString());
        //add方法修改時間
        calendar2.add(Calendar.HOUR,1);
        System.out.println(calendar2.getTime().toLocaleString());
        //補充方法
        calendar2.add(Calendar.MONTH,1);
        int max = calendar2.getActualMaximum(Calendar.DAY_OF_MONTH);
        int min = calendar2.getActualMinimum(Calendar.DAY_OF_MONTH);
        System.out.println(max);
        System.out.println(min);
    }
}

SimpleDateFormat類

public class Demo09 {
    public static void main(String[] args) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
        Date date = new Date();
        String str = sdf.format(date);
        System.out.println(str);
        //把字串轉換成日期
        Date date2 = sdf.parse("1997年01月13日23:59:59");
        System.out.println(date2);
    }
}

System類

主要用於獲取系統的屬性資料和其他操作,構造方法私有

方法名 說明
arraycopy() 複製陣列
long currentTimeMills() 獲取當前系統時間,返回毫秒值
gc() 建議JVM趕快啟動垃圾回收期回收垃圾
exit(int status) 退出JVM,如果引數是0表示正常退出JVM,非0表示異常退出JVM
public class Demo10 {
    public static void main(String[] args) {
        //arraycopy()陣列複製
        //src原陣列 srcPos從哪個位置開始複製0 dest目標陣列 destPos目標陣列位置 length:複製的長度
        int[] arr = {1,2,3,4,5,5,6,76,7,87,99,100};
        int[] arrd = new int[8];
        System.arraycopy(arr,0,arrd,0,arrd.length);
        for (int i : arrd) {
            System.out.println(i);
        }
        System.out.println(System.currentTimeMillis());
        long start = System.currentTimeMillis();
        for (int i = 0; i < 999999999; i++) {
            for (int j = 0; j <999999999 ; j++) {
                int result = i+j;
            }
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);  
    }
}