1. 程式人生 > 實用技巧 >13.常用API

13.常用API

常用API

Math

常用方法

方法名 說明
public static int abs(int a) 返回引數的絕對值
public static double ceil(double a) 返回大於或等於引數的最小double值, 等於一個整數
Public static double floor(double a) 返回小於或等於引數的最大double值, 等於一個整數
Public static int round(float a) 按照四捨五入返回最接近引數的int
public static int max(int a, int b) 返回int值中的較大值
public static int min(int a, int b) 返回int值中的較小值
public static double pow(double a, double b) 返回a的b次冪
Public static double random() 返回double的正值, [0.0, 1.0)

演示

package commonApi.math;

public class MathDemo {
    public static void main(String[] args) {
        System.out.println(Math.abs(-88));

        System.out.println("--------");
        System.out.println(Math.ceil(12.34));
        System.out.println(Math.ceil(12.56));

        System.out.println("--------");
        System.out.println(Math.floor(12.34));
        System.out.println(Math.floor(12.56));

        System.out.println("--------");
        System.out.println(Math.round(12.34F));
        System.out.println(Math.round(12.56F));

        System.out.println("--------");
        System.out.println(Math.max(66, 88));
        System.out.println(Math.min(66, 88));

        System.out.println("--------");
        System.out.println(Math.pow(2.0, 3.0));

        System.out.println("--------");
        System.out.println(Math.random());
        System.out.println(Math.random()*100);
        System.out.println((int)(Math.random()*100));
    }
}

System

system包含幾個有用的類欄位和方法, 它不能被例項化

system類的常用方法

方法名 說明
Public static void exit(int status) 終止當前執行的java虛擬機器, 非零表示異常終止
Public static long currentTimeMillis() 返回當前時間(以毫秒為單位)

demo

package commonApi.system;

public class SystemDemo {
    public static void main(String[] args) {
        System.out.println("start");
        // System.exit(0);  // 終止當前java虛擬機器
        System.out.println("end");

        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis()*1.0/1000/60/60/24/365 + "年");
    }
}

Object類

object是類層次結構的根, 每個類都可以將Object作為超類. 所有類都直接或者間接的繼承自該類.

構造方法: public Object()

子類構造方法預設訪問的是父類的無參構造方法? 因為頂級父類只有無參構造方法

常用方法

方法名 說明
public String toString() 返回物件的字串表示形式, 建議所有子類重寫該方法, 自動生成
public boolean equals(Object obj) 比較物件是否相等. 預設比較地址, 重寫可以比較內容, 自動生成

Student

package commonApi.object;

import java.util.Objects;

public class Student {
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        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 boolean equals(Object o) {
        /*
            this --- s2
            0    --- s3
         */
        // 比較地址是否相同
        if (this == o) return true;
        // 判斷引數是否為null
        // 判斷兩個物件是否來自同一個類
        if (o == null || getClass() != o.getClass()) return false;

        // 向下轉型
        Student student = (Student) o;  // student = s2
        // 比較年齡和姓名是否相同
        return age == student.age &&
                Objects.equals(name, student.name);
    }
}

ObjectDemo

package commonApi.object;

/*
    檢視原始碼,選中方法, Ctrl + B
 */

public class ObjectDemo {
    public static void main(String[] args) {
        Student s = new Student();
        s.setName("林青霞");
        s.setAge(30);
        System.out.println(s);  // commonApi.object.Student@27f674d
        System.out.println(s.toString());

        /*
        public void println(Object x) {
            String s = String.valueOf(x);
            synchronized (this) {
                print(s);
                newLine();
            }
        }
         */


        Student s2 = new Student();
        s2.setName("林青霞");
        s2.setAge(30);

        Student s3 = new Student();
        s3.setName("林青霞");
        s3.setAge(30);

        // 比較兩個物件是否相同
        System.out.println(s2 == s3);
        System.out.println(s2.equals(s3));
    }
}

Arrays

氣泡排序: 將一組資料按照固定的規則進行排序

氣泡排序: 一種排序規則, 對要進行排序的資料中相鄰的資料進行兩兩比較, 將較大的資料放在後面, 一次對所有的資料進行操作, 直至所有資料按要求完成排序.

如果有n個數據進行排序,總計需要比較n-1次

每次比較完畢,下一次比較就會少一個數據參與

BubbleSort

package commonApi.arrays;

public class BubbleSort {
    public static void main(String[] args) {
        int[] arr = {24, 69, 80, 57, 13};
        System.out.println("排序前:" + arrayToString(arr));

        // 氣泡排序對陣列排序過程
        /*
        for (int i=0; i<arr.length - 1; i++) {
            if (arr[i] > arr[i+1]) {
                int temp = arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = temp;
            }
        }
        System.out.println("第一次比較後:" + arrayToString(arr));

        for (int i=0; i<arr.length - 1 -1; i++) {
            if (arr[i] > arr[i+1]) {
                int temp = arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = temp;
            }
        }
        System.out.println("第二次比較後:" + arrayToString(arr));

        for (int i=0; i<arr.length - 1 -2; i++) {
            if (arr[i] > arr[i+1]) {
                int temp = arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = temp;
            }
        }
        System.out.println("第三次比較後:" + arrayToString(arr));

        for (int i=0; i<arr.length - 1 -3; i++) {
            if (arr[i] > arr[i+1]) {
                int temp = arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = temp;
            }
        }
        System.out.println("第四次比較後:" + arrayToString(arr));
        */
         // 優化版本
        for (int x=0; x<arr.length-1; x++) {
            for (int i=0; i<arr.length-1-x; i++) {
                if (arr[i] > arr[i+1]) {
                    int temp = arr[i];
                    arr[i] = arr[i+1];
                    arr[i+1] = temp;
                }
            }
        }
        System.out.println("排序後:" + arrayToString(arr));
    }

    // 把陣列中的元素排序並組成一個字串 [元素1, 元素2...]
    public static String arrayToString(int[] arr) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i=0; i<arr.length; i++){
            if (i == arr.length - 1) {
                sb.append(arr[i]);
            } else {
                sb.append(arr[i]).append(",");
            }
        }
        sb.append("]");
        String s = sb.toString();
        return s;
    }
}

Arrays類

Arrays類包含用於運算元組的各種方法

方法名 說明
public static String toString(int[] a) 返回指定陣列的內容的字串表現形式
public static void sort(int[] a) 按照數字順序排列指定的陣列

ArrayDemo

package commonApi.arrays;

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayDemo {
    public static void main(String[] args) {
        // 定義陣列
        int[] arr = {24, 69, 80, 57, 13};

        System.out.println("排序前:" + Arrays.toString(arr));
        Arrays.sort(arr);
        System.out.println("排序後:" + Arrays.toString(arr));
    }
}

工具類的設計思想:

  • 構造方法用private修飾
  • 成員用public static修飾

基本型別包裝類

將基本資料型別封裝為物件的好處在於可以在物件中定義更多的功能方法操作該資料

常用的操作之一: 用於基本資料型別與字串之間的轉換

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

Integer

integer: 包裝一個物件中的原始型別int的值

方法名 說明
public Integer(int value) 根據 int 值建立Integer物件(過時)
public Integer(String s) 根據String值建立Integer物件(過時)
public static Integer valueOf(int i) 返回表示指定的int值的Integer例項
public static Integer valueOf(String s) 返回一個儲存指定值的Integer物件String

demo

package commonApi.decorateClass;

public class IntegerDemo {
    public static void main(String[] args) {
        // 需求: 判斷一個整數在int 範圍內
        // public static final int MIN_VALUE
        // public static final int MAX_VALUE
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Integer.MAX_VALUE);

        /*
        // public Integer(int value)
        Integer i1 = new Integer(100);
        System.out.println(i1);

        // public Integer(String s)
        Integer i2 = new Integer("100");
        System.out.println(i2);
         */

        // public static Integer valueOf(int i)
        Integer i3 = Integer.valueOf(100);
        System.out.println(i3);

        // public static Integer valueOf(String s)
        Integer s4 = Integer.valueOf("100");
        System.out.println(s4);
    }
}

注意: 靜態方法不需要用new

int和String的相互裝換

基本型別包裝類的常見操作: 用於基本型別和字串之間的相互轉換

Int 轉換為String

  • public static String valueOf(int i): 返回int引數的字串形式. 該方法是String類中的方法

String 轉換為int

  • pulic static int parseInt(String s): 將字串解析為int型別. 該方法是Integer類中的方法

demo

package commonApi.decorateClass;

public class ConvertDemo {
    public static void main(String[] args) {
        // int --> String
        int number = 100;
        // 方式1
        String s1 = "" + number;
        System.out.println(s1);

        // 方式2
        String s2 = String.valueOf(number);
        System.out.println(s2);

        System.out.println("--------");
        // String -->  int
        String s = "100";
        // 方式1
        Integer i = Integer.valueOf(s);
        // public int intValue()
        int x = i.intValue();
        System.out.println(x);

        // 方式2
        // public static int parseInt(String s)
        int y = Integer.parseInt(s);
        System.out.println(y);
    }
}

自動裝箱和拆箱

裝箱: 把基本資料型別裝換為對應的包裝類型別

拆箱: 把包裝類型別轉換為對應的基本資料類型別

Integer i = 100; // 自動裝箱, 將基本型別int變為Integer
i += 200;  // i = i + 200; i + 200 自動拆箱; i = i + 200 自動裝箱

注意: 在使用包裝類型別時, 如果做操作, 最好先判斷是否為nulll

我們推薦的是, 只要是物件, 在使用錢就必須進行部位null 的判斷

PackAndUnpack

package commonApi.decorateClass;

public class PackAndUnpack {
    public static void main(String[] args) {
        // 裝箱: 把基本資料型別裝換為對應的包裝類型別
        Integer i = Integer.valueOf(100);
        Integer ii = 100;  // 自動裝箱, 底層也是呼叫: Integer.valueOf(100);

        //拆箱: 把包裝類型別轉換為對應的基本資料類型別
        // ii += 200;
        ii = ii.intValue() + 200;  // intValue拆箱後變成基本型別
        System.out.println(ii);

        ii += 200;  // 自動拆箱, 底層也是呼叫: Integer.intValue(ii);
        System.out.println(ii);

        Integer iii = null;
        // iii += 300;  //NullPointerException
        if (iii != null) {
            iii += 300;
        }
        System.out.println(iii);

    }
}

日期類

date類

date類代表了一個特定的時間, 精確到毫秒

構造方法

方法名 說明
public Date() 分配一個Date物件, 並初始化, 以便它代表被分配的時間, 精確到毫秒
pulic Date(long date) 分配一個Date物件, 並將其初始化為表示從標準基準時間起指定的毫秒數

常見方法

方法名 說明
public long getTime() 獲取的是日期物件從1970年1月1日00:00:00到現在的毫秒值
public void setTime() 設定時間, 給的是毫秒值

DateDemo

package commonApi.decorateClass;

import java.util.Date;

public class DateDemo {
    public static void main(String[] args) {
        // public Date()

        Date d1 = new Date();
        System.out.println(d1);

        // public Date(long date):
        long date = 1000*60*60;
        Date d2 = new Date(date);
        System.out.println(d2);


        // 建立時間日期物件
        Date d = new Date();
        // public long getTime()
        System.out.println(d.getTime()*1.0/1000/60/60/24/365 + "年");

        // public void setTime()
        long time = 1000*60*60;
        d.setTime(time);
        System.out.println(d);
        
        long time1 = System.currentTimeMillis();
        d.setTime(time1);
        System.out.println(d);
    }
}

SimpleDateFormat類

SimpleDateFormat是一個具體類, 用於以區域設定敏感的方式格式化和解析日期. 重點學習日期格式化和解析

日期和時間格式有日期和時間模式字串指定, 在日期和時間模式字串中, 從"A"到"Z"以及從"a" 到 "z"引號的字幕被解釋為表示日期或時間字串的元件的模式字母.

常見模式字母對應:

  • y 年
  • M 月
  • d 日
  • H 時
  • m 分
  • s 秒

構造方法

方法名 說明
public SimpleDateFormat() 構造一個SimpleDateFormat, 使用預設模式和日期格式
public SimpleDateFormat() 構造一個SimpleDateFormat, 使用給定的模式和預設的日期格式

格式化和解析方法

  1. 格式化(從Date到String)

    • public final String format(Date date): 將日期格式化為日期/時間字串
  2. 解析(從String到Date)

    • public Date parse(String source): 從給定的字串的開始解析文字以生成日期

SimpleDateFormatDemo

package commonApi.decorateClass;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatDemo {
    public static void main(String[] args) throws ParseException {
        // 格式化: 從Date 到 String
        Date d = new Date();
        // SimpleDateFormat sdf = new SimpleDateFormat();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String s = sdf.format(d);
        System.out.println(s);

        // 解析: 從 String 到 Date
        String s1 = "2020-10-14 11:11:11";
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d2 = sdf2.parse(s1);
        System.out.println(d2);
    }
}

Calendar類

為某一時刻和一組日曆欄位的轉換提供了一些方法, 併為操作日曆欄位提供了一些方法

  • 提供了一個getInstance用於獲取Calendar物件, 其日曆欄位已使用當前日期和時間初始化;
  • Calendar rightNow = Calendar.getInstance();

常用方法

方法名 說明
public int get(int field) 返回給定日曆欄位的值
public abstract void add(int field, int amount) 根據日曆的規則, 將指定的時間量新增或者減去給定的日曆欄位
Public final void set(int year, int month, int date) 設定當前日曆的年月日

CalendarDemo

package commonApi.decorateClass;

import java.util.Calendar;

public class CalendarDemo {
    public static void main(String[] args) {
        // 獲取物件
        Calendar c = Calendar.getInstance();  // 多型形式得到物件
        System.out.println(c);

        // public int get(int field)
        /*
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int date = c.get(Calendar.DATE);
        System.out.println(year + "年" + month + "月" + date + "日");

         */

        // public abstract void add(int field, int amount)
        // 10年後的5天前
        /*
        c.add(Calendar.YEAR, 10);
        c.add(Calendar.DATE, -5);
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int date = c.get(Calendar.DATE);
        System.out.println(year + "年" + month + "月" + date + "日");

         */

        //Public final void set(int year, int month, int date)
        c.set(2030, Calendar.NOVEMBER,20);
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int date = c.get(Calendar.DATE);
        System.out.println(year + "年" + month + "月" + date + "日");
    }
}