Java常用API(2020)

1. Java常用API(2020)

  • Object類/Scanner類
  • String類/StringBuffer類/StringBuilder類
  • 數組高級和Arrays類
  • 基本類型包裝類(Integer,Character)
  • 正則表達式(Pattern,Matcher)
  • Math類/Random類/System類
  • BigInteger類/BigDecimal類
  • Date類/DateFromat類/Calendar類

1.1 Object類,java.lang.Object

Object類是所有類的根類,所有類都直接或間接的繼承自該類。

1.1.1 成員方法

  • int hashCode(),返回該對象的哈希值。哈希值是對象的邏輯地址值,非物理地址值。
  • Class getClass(),返回Object的運行時類對象,Class是一個類型,是字節碼文件*.class。
  • String toString(),返回對象的文本表現形式,如果沒有重寫由三部分組成,全路徑+@+16進制邏輯內存地址值,System.out.println(此處默認調用.toString)。
  • boolean equals(Object obj),首先判斷地址值是否相同,如果不同則爲false,不同的object重寫後不一樣,但是會挨個比較其中的值,如果值相同,則爲true。
  • protected void finalize(),對象無引用,回收該對象,方法需要重寫。
  • protected void clone(),克隆對象的地址和原地址不同,引用對象的地址和原地址相同。

1.1.2 Demo

package com.xzy.JavaUsedAPI.java.lang.Object;

import java.util.Objects;

public class Student extends Object implements Cloneable {
    private String name;
    private Integer age;


    public Student() {
    }

    public String getName() {
        return name;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    }

    //Student中默認重寫equals方法
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(name, student.name) &&
                Objects.equals(age, student.age);
    }

    //仿照重寫equals方法
    public boolean equals2(Object o) {
        Student s = (Student) o;
        if (this.name.equals(s.getName()) && this.age == s.getAge()) {
            return true;
        } else {
            return false;
        }
    }

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

    public Integer getAge() {
        return age;
    }

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

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int hashCode() {
        return super.hashCode();//默認方法
        //  return 10;//重寫方法
    }

    //未重寫toString
    @Override
    public String toString() {
        return super.toString();
    }

    //源碼方法
    //public String toString() {
    //  return getClass().getName() + "@" + Integer.toHexString(hashCode());
    //}
    //仿照源碼重寫toString,作爲普通方法調用
    public String toString2() {
        //Integer類的toHexString方法可以將10進制轉換成16進制並以字符串返回
        String str = Integer.toHexString(this.hashCode());//調用本類this可省略
        return this.getClass().getName() + "@" + str;//調用本類this可省略
    }

    //自定義toString方法
    public String toString3() {
        return name + ":" + age;
    }
}

package com.xzy.JavaUsedAPI.java.lang.Object;

public class ObjectP {
    public static void main(String[] args) throws Throwable {
        //int hashCode()
        Student s1 = new Student();
        Student s2 = new Student();
        int h1 = s1.hashCode();
        int h2 = s2.hashCode();
        System.out.println(h1);
        System.out.println(h2);
        System.out.println("----------1--------");
        //Class getClass()
        Class clazz1 = s1.getClass();
        Class clazz2 = s2.getClass();
        System.out.println(clazz1);
        System.out.println(clazz2);
        String name = clazz1.getName();
        System.out.println(name);
        System.out.println("-----------2-------");
        //String toString()
        String s3 = s1.toString();
        String s4 = s2.toString();
        String s5 = s2.toString2();
        System.out.println(s3);
        System.out.println(s4);
        System.out.println(s5);
        Student joshua = new Student("Joshua", 20);
        System.out.println(joshua.toString3());
        System.out.println("----------3--------");
        //boolean equals(Object obj)
        Student jack = new Student("Jack", 11);
        Student ben = new Student("Ben", 12);
        Student ben2 = new Student("Ben", 12);
        Student mm=jack;
        System.out.println(mm == jack);
        System.out.println(ben == jack);
        System.out.println(ben == ben2);
        //***==在基本數據類型中比較的是值,在引用和對象中比較的是對象的邏輯內存地址
        System.out.println(ben.equals(jack));
        String hello1 = new String("hello");
        String hello2 = new String("hello");
        System.out.println(hello1.equals(hello2));//邏輯內存地址不一樣,堆中的值一樣。String繼承自Object類並重寫了equals方法,先比較內存地址值是否相等,再比較值是否相等。
        System.out.println(hello1==hello2);//比較的是對象的邏輯內存地址值。
        System.out.println(ben2.equals2(ben));
        //void finalize();
        jack.finalize();
        //void clone();
        //一個對象是否能克隆要看該對象是否實現了一個標記接口clonable
        Student student1 = new Student();
        Student student2 = student1;
        //student1和student2是同一個對象,其中student2是student1的引用.
        Object clone = student1.clone();
        Student student3 = (Student) clone;
        System.out.println(student3);
        System.out.println(student1);
    }
}

1.2 Scanner類,java.util.Scanner

1.2.1 構造方法

  • Scanner(InputStream source)構造一個新的 Scanner,它生成的值是從指定的輸入流掃描的。

1.2.2 成員方法

  • String next(),有效字符前面有空格、tab、回車時next()會忽略,next()接收的字符串中不包含空格、tab、回車,next()以回車作爲結束的標誌。
  • String nextLine(),可以接收空格、tab,以回車鍵作爲結束的標誌。

1.2.3 Demo

package com.xzy.JavaUsedAPI.java.util.Scanner;

import java.util.Scanner;

public class ScannerP {
    public static void main(String[] args) {

    }

    private static void partOne() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("please input a number:");
        if (scanner.hasNextInt()) {
            String st = scanner.nextLine();
            System.out.println(st);
        }else {
            System.out.println("error");
        }
        Scanner scanner1 = new Scanner(System.in);
        System.out.println("請輸入任意字符");
        String next = scanner1.next();
        System.out.println(next);
        System.out.println("----------------------");
    }
}

1.3 String類,java.lang.String

1.3.1 構造方法

  • String(byte[] bytes)通過使用平臺的默認字符集解碼指定的 byte 數組,構造一個新的 String。
  • String(byte[] bytes, int offset, int length)通過使用平臺的默認字符集解碼指定的 byte 子數組,構造一個新的 String。
  • String(char[] value)分配一個新的 String,使其表示字符數組參數中當前包含的字符序列。
  • String(char[] value, int offset, int count)分配一個新的 String,它包含取自字符數組參數一個子數組的字符。

1.3.2 成員方法

  • boolean equals(Object anObject)將此字符串與指定的對象比較。
  • boolean equalsIgnoreCase(String anotherString)將此 String 與另一個 String 比較,不考慮大小寫。
  • boolean contains(CharSequence s)當且僅當此字符串包含指定的 char 值序列時,返回 true。
  • boolean startsWith(String prefix)測試此字符串是否以指定的前綴開始。
  • boolean endsWith(String suffix)測試此字符串是否以指定的後綴結束。
  • boolean isEmpty()當且僅當 length() 爲 0 時返回 true。
  • int length()返回此字符串的長度。
  • char charAt(int index)返回指定索引處的 char 值。
  • int indexOf(int ch)返回指定字符在此字符串中第一次出現處的索引。
  • int indexOf(String str)返回指定子字符串在此字符串中第一次出現處的索引。
  • int indexOf(int ch, int fromIndex)返回在此字符串中第一次出現指定字符處的索引,從指定的索引開始搜索。
  • int indexOf(String str, int fromIndex)返回指定子字符串在此字符串中第一次出現處的索引,從指定的索引開始。
  • String substring(int beginIndex)返回一個新的字符串,它是此字符串的一個子字符串。
  • String substring(int beginIndex, int endIndex)返回一個新字符串,它是此字符串的一個子字符串。
  • byte[] getBytes()使用平臺的默認字符集將此 String 編碼爲 byte 序列,並將結果存儲到一個新的 byte 數組中。
  • char[] toCharArray()將此字符串轉換爲一個新的字符數組。
  • String toLowerCase()使用默認語言環境的規則將此 String 中的所有字符都轉換爲小寫。
  • String toUpperCase()使用默認語言環境的規則將此 String 中的所有字符都轉換爲大寫。
  • String concat(String str)將指定字符串連接到此字符串的結尾。
  • static String valueOf(char[] data)返回 char 數組參數的字符串表示形式。
  • static String valueOf(int i)返回 int 參數的字符串表示形式。
  • static String valueOf(Object obj)返回Object參數的字符串表示形式。
  • String replace(char old,char new)
  • String replace(String old,String new)
  • String trim()
  • int compareTo(String str)
  • int compareToIgnoreCase(String str)

1.3.3 Demo

package com.xzy.JavaUsedAPI.java.lang.String;

import java.util.Date;
import java.util.Scanner;

import static java.lang.String.valueOf;

public class StringP {
    public static void main(String[] args) {

    }

    private static void part21() {
        String str1 = "adasdadjavafffffffffosoagknlaskdjlfnblaskdfjava";
        String findStr="java";
        int count = 0;
        int indexOf = str1.indexOf(findStr);
        while (indexOf!=-1) {
            count++;
            int newIndex = indexOf + findStr.length();
            str1=str1.substring(newIndex);
            indexOf= str1.indexOf(findStr);
        }
        System.out.println("字符串出現的次數爲:"+count);
    }

    private static void part20() {
        StringBuilder stringBuilder = new StringBuilder("12345");
        StringBuilder reverse = stringBuilder.reverse();
        System.out.println(reverse.toString());
    }

    private static void part19() {
        String str1 = "abcdefghijklmn12121212AAAAAAAAAAAAAA";
        String substring1 = str1.substring(0, 3);
        System.out.println(substring1);
        String s = substring1.toUpperCase();
        System.out.println(s);
    }

    private static void part18() {
        String str1 = "abcdefghijklmn12121212AAAAAAAAAAAAAA";
        StringBuilder num = new StringBuilder();
        StringBuilder big = new StringBuilder();
        StringBuilder small = new StringBuilder();
        Integer numCount = 0;
        Integer bigCount = 0;
        Integer smallCount = 0;
        char[] chars = str1.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] >= '0' && chars[i] <= '9') {
                num.append(chars[i]);
                numCount++;
            } else if (chars[i] >= 'A' && chars[i] <= 'Z') {
                big.append(chars[i]);
                bigCount++;
            } else if (chars[i] >= 'a' && chars[i] <= 'b') {
                small.append(chars[i]);
                smallCount++;
            }
        }
        System.out.println(num.toString() + "\t出現了" + numCount + "次");
        System.out.println(big.toString() + "\t出現了" + bigCount + "次");
        System.out.println(small.toString() + "\t出現了" + smallCount + "次");

        {
            //清空
            num = null;
            big = null;
            small = null;
            numCount = null;
            bigCount = null;
            smallCount = null;
        }
    }

    private static void part17() {
        String str1 = "abcdefghijklmn";
        char[] chars = str1.toCharArray();
        for (char aChar : chars) {
            System.out.print("[" + aChar + "]" + ",");
        }
        System.out.println();
        for (int i = 0; i < str1.length(); i++) {
            System.out.print("[" + str1.charAt(i) + "]" + ",");
        }
    }

    private static void part16() {
        String username = "admin";
        String password = "admin";
        StringBuilder log = new StringBuilder();
        System.out.println("你只有三次機會輸入用戶名和密碼");
        for (int i = 1; i <= 3; i++) {
            System.out.print("請輸入用戶名:");
            Scanner scanner = new Scanner(System.in);
            String usernameInput = scanner.nextLine();
            log.append(new Date() + "\tusername" + usernameInput + "\n");
            System.out.print("請輸入密碼:");
            String passwordInput = scanner.nextLine();
            log.append(new Date() + "\tpassword:" + passwordInput + "\n");
            if (username.compareTo(usernameInput) == 0 && password.compareTo(passwordInput) == 0) {
                //equals和compareTo好像一樣,歡迎點評
                System.out.println("login success");
                part15();
                System.out.println("系統登錄日誌:\n" + log);
                log = null;//清空
                break;
            } else {
                System.out.println("賬號或者密碼錯誤!" + "剩餘次數" + (3 - i));
            }
        }
    }

    private static void part15() {
        int j = (int) ((Math.random() * 100) + 1);
        int count = 0;
        while (true) {
            count++;
            System.out.println("我已經生成數字[1,100],請輸入一個數字:");
            Scanner scanner = new Scanner(System.in);
            if (scanner.hasNextInt()) {
                int i = scanner.nextInt();
                if (i > j) {
                    System.out.println("你輸入的數字大了");
                } else if (i < j) {
                    System.out.println("你輸入的數字小了");
                } else {
                    System.out.println("猜中了" + i + "," + count + "次");
                    break;
                }
            } else {
                System.out.println("格式不對,請輸入一個int類型的數字!");
            }
        }
    }

    private static void part14() {
        String str1 = "abcde";
        String str2 = "abcde";
        String str3 = "bbcde";
        String str4 = "fghijkl";
        String str5 = "abcdef";
        String str6 = "Abcde";
        Integer integer = Integer.valueOf(str4.charAt(0));
        int compareTo = str1.compareTo(str2);
        System.out.println(compareTo);
        int i = str1.compareTo(str3);
        System.out.println(i);
        int j = str1.compareTo(str4);
        System.out.println(j);
        System.out.println(integer);
        int i1 = str1.compareTo(str5);
        System.out.println(i1);
        int i2 = str6.compareToIgnoreCase(str1);
        System.out.println(i2);
    }

    private static void part13() {
        String str1 = "aaaaaaaaasdadadasdsfnkflsafnkalsdnjakldad";
        String replace = str1.replace('a', 'k');
        String replace1 = str1.replace("da", "II");
        System.out.println(replace);
        System.out.println(replace1);
        String str2 = "   adadaad    dadadad    ";
        String trim = str2.trim();
        System.out.println(trim);
    }

    private static void part12() {
        char[] chars = {'a', 'b', 'c'};
        String s = valueOf(chars);
        String s1 = valueOf(10);
        System.out.println(s);
        System.out.println(s1.charAt(0));
        System.out.println(s1.charAt(1));
        String s2 = valueOf(new Demo());
        System.out.println(s2);
    }

    private static void part11() {
        String str1 = "aaa";
        String str2 = "bbb";
        String concat = str1.concat(str2);//concat只能拼接字符串,如果爲null則空指針異常,加號可以拼接任意類型且一邊爲null不會報空指針異常。
        System.out.println(concat);
    }

    private static void part10() {
        String str1 = "woaixuejava";
        byte[] bytes = str1.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            System.out.print((char) bytes[i]);
        }
        System.out.println("---------------------");
        char[] chars = str1.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            System.out.print(chars[i]);
        }
        System.out.println("---------------------");
        String s = str1.toUpperCase();
        System.out.println(s);
        String s1 = str1.toLowerCase();
        System.out.println(s1);
    }

    private static void part9() {
        String str1 = "abcdefghijklmn";
        String substring1 = str1.substring(str1.indexOf('b'), str1.indexOf('f') + 1);
        System.out.println(substring1);
    }

    private static void part8() {
        String str1 = "abcdefgh";
        String str2 = "cd";
        System.out.println(str1.indexOf(str2));
        int i = str1.indexOf(str2, 3);
        System.out.println(i);
        int a = str1.indexOf('a', 0);
        System.out.println(a);
    }

    private static void part7() {
        String str1 = "abcde";
        String s = valueOf(str1.charAt(1));
        System.out.println(s);
        int a = str1.indexOf('a');
        System.out.println(a);
    }

    private static void part6() {
        String str1 = "abcde";
        String str2 = valueOf(str1.charAt(0));
        String str3 = valueOf(str1.charAt(str1.length() - 1));
        System.out.println(str2);
        System.out.println(str1.startsWith(str2));
        System.out.println(str3);
        System.out.println(str1.endsWith(str3));
        String str4 = "";//str4爲空
        String str5 = null;//str5未指向任何物理邏輯地址,空引用
        System.out.println(str4.isEmpty());
        System.out.println(str5.isEmpty());
        System.out.println("----");
        System.out.println(str4.length());
        System.out.println(str5.length());
    }

    private static void part5() {
        String str1 = "abc";
        String str2 = new String("Abc");
        String str3 = "a";
        System.out.println(str1.equals(str2));
        System.out.println(str1.equalsIgnoreCase(str2));
        System.out.println(str1.contains(str3));
    }

    private static void part4() {
        String str1 = new String("sdadadad");
        String str2 = new String("1111111111111");
        String str3 = str1 + str2;
        System.out.println(str3);
        //1、一個變量字符串加常量之後的結果是變量
        //2、字符串常量的值是不能改變的
        //***變量和誰相加都是變量,兩個常量相加纔是常量
    }

    private static void part3() {
        char[] chars = {'a', 'b', 'c'};
        String s = new String(chars);
        String s1 = new String(chars, 1, 2);
        System.out.println(s);
        System.out.println(s1);
    }

    public static void part2() {
        byte[] bytes = {97, 99, 100};
        String s = new String(bytes);
        String s1 = new String(bytes, 1, 2);
        System.out.println(s1);
        System.out.println(s);
        System.out.println(s.length());
        System.out.println(s1.length());
    }

    private static void part1() {
        String str1 = "abc";//字符串常量,常量放在常量池中的方法區
        String str2 = new String("abc");//堆內存中
        int length = str2.length();
        System.out.println(str2);
        System.out.println(length);
    }
}

package com.xzy.JavaUsedAPI.java.lang.String;

public class Demo {
    @Override
    public String toString() {
        return "OK";
    }
}

1.4 StringBuffer類,java.lang.StringBuffer

StringBuffer是帶緩衝區的字符串,長度和內容可以改變。
StringBuffer線程是安全的,線程安全的優點是數據安全,缺點是效率低。

1.4.1 構造方法

  • StringBuffer(int capacity)構造一個不帶字符,但具有指定初始容量的字符串緩衝區。
  • StringBuffer(String str)構造一個字符串緩衝區,並將其內容初始化爲指定的字符串內容。
  • StringBuffer()構造一個其中不帶字符的字符串緩衝區,其初始容量爲 16 個字符。

1.4.2 成員方法

  • StringBuffer append(String str)將指定的字符串追加到此字符序列。
  • StringBuffer insert(int offset,String str)將字符串插入此字符序列中。
  • StringBuffer delelteChart(int index)移除此序列指定位置的 char。
  • StringBuffer delete(int start,int end)移除此序列的子字符串中的字符。
  • StringBuffer replace(int start.int end,String str)使用給定 String 中的字符替換此序列的子字符串中的字符。
  • StringBuffer reverse()將此字符序列用其反轉形式取代。
  • String substring(int start)返回一個新的 String,它包含此字符序列當前所包含的字符子序列。
  • String substring(int start,int end)返回一個新的 String,它包含此序列當前所包含的字符子序列。

1.4.3 Demo

package com.xzy.JavaUsedAPI.java.lang.StringBuffer;

public class StringBufferP {
    public static void main(String[] args) {

    }

    private static void part7() {
        StringBuffer hellojava = new StringBuffer("hellojava");
        String substring = hellojava.substring(3);
        System.out.println(hellojava);
        System.out.println(substring);
        String substring1 = hellojava.substring(0, 5);
        System.out.println(substring1);
        System.out.println(hellojava);
    }

    private static void part6() {
        StringBuffer hellojava = new StringBuffer("hellojava");
        hellojava.reverse();
        System.out.println(hellojava);
    }

    private static void part5() {
        StringBuffer hellojava = new StringBuffer("hellojava");
        hellojava.replace(0,5,"hasdasdadhhhh");
        System.out.println(hellojava);
    }

    private static void part4() {
        StringBuffer helloword = new StringBuffer("helloword");
        helloword.deleteCharAt(0);
        helloword.deleteCharAt(3);
        helloword.delete(0,3);//包左不包右
        System.out.println(helloword);
    }

    private static void part3() {
        StringBuffer java = new StringBuffer("java");
        StringBuffer hello = java.insert(0, "hello");
        System.out.println(java);
        System.out.println(hello);
        char[] chars={'a','b','c'};
        java.insert(0,chars,0,1);
        System.out.println(java);
    }

    private static void part2() {
        StringBuffer java = new StringBuffer("java");
        StringBuffer hello = java.append("hello");
        System.out.println(java.capacity());
        System.out.println(hello.capacity());
        System.out.println(java);
        System.out.println(hello);
        System.out.println(java == hello);

        StringBuffer append = java.append(20);
        System.out.println(java);
        System.out.println(append);

        StringBuffer append1 = java.append(true);
        System.out.println(java);
        System.out.println(append1);
    }

    private static void part1() {
        StringBuffer stringBuffer = new StringBuffer();
        int capacity = stringBuffer.capacity();
        System.out.println(capacity);//字符緩衝區容量是緩衝區大小,容量可自動擴容
        System.out.println(stringBuffer.length());//長度是字符緩衝區實際字符的個數
        StringBuffer stringBuffer1 = new StringBuffer(20);
        System.out.println(stringBuffer1.capacity());
        System.out.println(stringBuffer1.length());
        StringBuffer java = new StringBuffer("java");
        System.out.println(java.capacity());
        System.out.println(java.length());//默認容量16+
    }
}

1.5 常用排序算法

1.5.1 冒泡排序

  • 相鄰元素兩兩比較,大的往後放,小的往前放,第一次完畢,最大值出現在了最大索引處。除最大元素外,剩餘的元素以此類推。

  • 外j內i,for循環0到對象的長度-1、-j-1,循環體爲arr[i]>arr[i+1].if,int temp;temp=arr[i];arr[i]=arr[i+1];arr[i+1]=temp;

    package com.xzy.JavaUsedAPI.Arithmetic;

    public class BinarySearch {
    public static void main(String[] args) {

      }
    
      private static void characterSort() {
          String str1 = "jklmnabcdefghi";
          char[] ch = str1.toCharArray();
          int[] arr=new int[str1.length()];
          for (int i = 0; i < ch.length; i++) {
              arr[i]=(int)ch[i];
          }
    
          for (int j = 1; j < arr.length; j++) {
              for (int i = 0; i < arr.length - 1; i++) {
                  if (arr[i] > arr[j]) {
                      int temp;
                      temp = arr[j];
                      arr[j] = arr[i];
                      arr[i] = temp;
                  }
              }
          }
          for (int i = 0; i < arr.length; i++) {
              ch[i]=(char)arr[i];
          }
          String s = String.valueOf(ch);
          System.out.println("排序後:"+s);
      }
    
      private static void binarySort() {
          int[] arr = getArr();
          int[] num = new int[1];
          if ((int) (Math.random() * 2 + 1) == 1) {
              num[0] = arr[(int) (Math.random() * 9 + 0)];
          } else {
              num[0] = (int) (Math.random() * 1000 + 1);
          }
          System.out.println("我這次要猜的數字是:" + num[0]);
          int min = 0;
          int max = arr.length - 1;
          int mid = (min + max) / 2;
          while (true) {
              if (num[0] >= arr[min] && num[0] <= arr[max]) {
                  if (num[0] > arr[mid]) {
                      min = mid + 1;
                      mid = (min + max) / 2;
                  } else if (num[0] < arr[mid]) {
                      max = mid - 1;
                      mid = (min + max) / 2;
                  } else if (num[0] == arr[mid]) {
                      System.out.println("值找到了,數據的索引是" + mid);
                      break;
                  }
    
              } else {
                  System.out.println("您查找的值不存在");
                  break;
              }
          }
      }
    
      private static int[] getArr() {
          int[] arr = GenerateRandomNumber();
          for (int j = 1; j < arr.length; j++) {
              for (int i = 0; i < arr.length - 1; i++) {
                  if (arr[i] > arr[j]) {
                      int temp;
                      temp = arr[j];
                      arr[j] = arr[i];
                      arr[i] = temp;
                  }
              }
          }
          System.out.println("排序後:");
          for (int i : arr) {
              System.out.print(i + ",");
          }
          System.out.println();
          return arr;
      }
    
      private static int[] GenerateRandomNumber() {
          int[] arr = new int[10];
          for (int i = 0; i < arr.length; i++) {
              arr[i] = (int) (Math.random() * 100 + 1);
              for (int j = 0; j < i; j++) {
                  if (arr[i] == arr[j]) {
                      i--;
                      break;
                  }
              }
          }
          System.out.println("生成的隨機數爲:");
          for (int i : arr) {
              System.out.print(i + ",");
          }
          System.out.println();
          return arr;
      }
    

    }

1.5.2 選擇排序

  • 從最小索引開始,依次選擇每個元素和其他所有的元素進行比較,小的放在小的索引處。

  • 外j內i,外for循環1到對象長度,內for循環0到對象長度-1,循環體爲arr[i]>arr[j].if,int temp;temp=arr[j];arr[j]=arr[i];arr[i]=temp;

    package com.xzy.JavaUsedAPI.Arithmetic;

    public class SelectionSort {
    public static void main(String[] args) {
    int[] arr = GenerateRandomNumber();
    for (int j = 1; j < arr.length; j++) {
    for (int i = 0; i < arr.length-1; i++) {
    if (arr[i]>arr[j]) {
    int temp;
    temp=arr[j];
    arr[j]=arr[i];
    arr[i]=temp;
    }
    }
    }
    System.out.println(“排序後:”);
    for (int i : arr) {
    System.out.print(i+",");
    }

      }
      private static int[] GenerateRandomNumber() {
          int[] arr = new int[10];
          for (int i = 0; i < arr.length; i++) {
              arr[i]= (int) (Math.random() * 100 + 1);
              for (int j = 0; j < i; j++) {
                  if (arr[i]==arr[j]) {
                      i--;
                      break;
                  }
              }
          }
          System.out.println("生成的隨機數爲:");
          for (int i : arr) {
              System.out.print(i+",");
          }
          System.out.println();
          return arr;
      }
    

    }

1.6 常用查找算法

1.6.1 基本查找

循環遍歷某個值在某個對象中是否存在並返回索引

package com.xzy.JavaUsedAPI.Arithmetic;

public class BasicSearch {
    public static void main(String[] args) {
        int[] arr1 = GenerateASetOfRandomNumbers();
        int[] num = new int[1];
        int[] index = new int[10];
        num[0]=arr1[(int)(Math.random()*10+0)];
        System.out.println("生成一個組中的數據爲:\n"+num[0]);
        for (int i = 0; i < arr1.length; i++) {
            if (arr1[i]==num[0]) {
                index[0]=i;

            }
        }
        System.out.println("已查找到數據,位於原數組的第" + (index[0] + 1) + "個元素");
        System.out.println("查找的數據值爲:"+arr1[index[0]]);

    }

    private static int[] GenerateASetOfRandomNumbers() {
        int[] arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * 100 + 1);
            for (int j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    i--;
                    break;
                }
            }
        }
        System.out.println("生成一組隨機數爲:");
        for (int i : arr) {
            System.out.print(i + ",");
        }
        System.out.println();
        return arr;
    }
}

1.6.2 二分查找

前提是數組是有序的

package com.xzy.JavaUsedAPI.Arithmetic;

public class BinarySearch {
    public static void main(String[] args) {

    }

    private static void characterSort() {
        String str1 = "jklmnabcdefghi";
        char[] ch = str1.toCharArray();
        int[] arr=new int[str1.length()];
        for (int i = 0; i < ch.length; i++) {
            arr[i]=(int)ch[i];
        }

        for (int j = 1; j < arr.length; j++) {
            for (int i = 0; i < arr.length - 1; i++) {
                if (arr[i] > arr[j]) {
                    int temp;
                    temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                }
            }
        }
        for (int i = 0; i < arr.length; i++) {
            ch[i]=(char)arr[i];
        }
        String s = String.valueOf(ch);
        System.out.println("排序後:"+s);
    }

    private static void binarySort() {
        int[] arr = getArr();
        int[] num = new int[1];
        if ((int) (Math.random() * 2 + 1) == 1) {
            num[0] = arr[(int) (Math.random() * 10 + 0)];
        } else {
            num[0] = (int) (Math.random() * 1000 + 1);
        }
        System.out.println("我這次要猜的數字是:" + num[0]);
        int min = 0;
        int max = arr.length - 1;
        int mid = (min + max) / 2;
        while (true) {
            if (num[0] >= arr[min] && num[0] <= arr[max]) {
                if (num[0] > arr[mid]) {
                    min = mid + 1;
                    mid = (min + max) / 2;
                } else if (num[0] < arr[mid]) {
                    max = mid - 1;
                    mid = (min + max) / 2;
                } else if (num[0] == arr[mid]) {
                    System.out.println("值找到了,數據的索引是" + mid);
                    break;
                }

            } else {
                System.out.println("您查找的值不存在");
                break;
            }
        }
    }

    private static int[] getArr() {
        int[] arr = GenerateRandomNumber();
        for (int j = 1; j < arr.length; j++) {
            for (int i = 0; i < arr.length - 1; i++) {
                if (arr[i] > arr[j]) {
                    int temp;
                    temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                }
            }
        }
        System.out.println("排序後:");
        for (int i : arr) {
            System.out.print(i + ",");
        }
        System.out.println();
        return arr;
    }

    private static int[] GenerateRandomNumber() {
        int[] arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * 100 + 1);
            for (int j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    i--;
                    break;
                }
            }
        }
        System.out.println("生成的隨機數爲:");
        for (int i : arr) {
            System.out.print(i + ",");
        }
        System.out.println();
        return arr;
    }
}

1.7 Arrays類,java.util.Arrays

1.7.1 成員方法

  • static int binarySearch(int[] a, int key)使用二分搜索法來搜索指定的 int 型數組,以獲得指定的值。
  • static String toString(short[] a)返回指定數組內容的字符串表示形式。

1.7.2 Demo

package com.xzy.JavaUsedAPI.java.util.Arrays;

import java.util.Arrays;

public class ArraysP {
    public static void main(String[] args) {

    }

    private static void part2() {
        int[] arr = GenerateRandomNumber();
        System.out.println(arr);
        String s = Arrays.toString(arr);
        System.out.println(s);
    }

    private static void part1() {
        int[] arr = GenerateRandomNumber();
        Arrays.sort(arr);
        System.out.println("排序後的數據爲:");
        for (int i : arr) {
            System.out.print(i+",");
        }
        System.out.println();
        int index=arr[(int) (Math.random() * 10 + 0)];
        System.out.println("查找的值爲:"+index);
        int i = Arrays.binarySearch(arr, index);
        System.out.println("查找的索引爲"+i);
    }

    private static int[] GenerateRandomNumber() {
        int[] arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i]= (int) (Math.random() * 100 + 1);
            for (int j = 0; j < i; j++) {
                if (arr[i]==arr[j]) {
                    i--;
                    break;
                }
            }
        }
        System.out.println("生成的隨機數爲:");
        for (int i : arr) {
            System.out.print(i+",");
        }
        System.out.println();
        return arr;
    }
}

1.8 基本數據類型及包裝類

  • byte,Byte
  • short,Short
  • int,Integer
  • long,Long
  • float,Float
  • double,Double
  • char,Character
  • boolean,Boolean

1.9 Integer類,java.lang.Integer

1.9.1 構造方法

  • Integer(int value)構造一個新分配的 Integer 對象,它表示指定的 int 值。
  • Integer(String s)構造一個新分配的 Integer 對象,它表示 String 參數所指示的 int 值。

1.9.2 成員方法

  • static String toString(int i, int radix)返回用第二個參數指定基數表示的第一個參數的字符串表示形式。
  • static String toBinaryString(int i)以二進制(基數 2)無符號整數形式返回一個整數參數的字符串表示形式。
  • static String toHexString(int i)以十六進制(基數 16)無符號整數形式返回一個整數參數的字符串表示形式。
  • static String toOctalString(int i)以八進制(基數 8)無符號整數形式返回一個整數參數的字符串表示形式。

1.9.3 Demo

package com.xzy.JavaUsedAPI.java.lang.Integer;



public class IntegerP {
    public static void main(String[] args) {

    }

    private static void part6() {
        //如果int是-128-127之間的話,java會從緩存池中拿,如果不是則會new一個對象new Integer(value)
        Integer integer = new Integer(100);
        Integer i=100;//Integer.valueOf(100)
        i=i+1000;
        System.out.println(integer);
        System.out.println(i);
    }

    private static void part5() {
        //2-36進制有效,0-9+a-z
        int num=100;
        String s = Integer.toString(num, 8);
        System.out.println(s);
        String s1 = Integer.toString(num, 2);
        System.out.println(s1);
        String s2 = Integer.toString(num, 20);
        System.out.println(s2);
        String s3 = Integer.toString(num, 100);
        System.out.println(s3);
        String s4 = Integer.toString(num, 50);
        System.out.println(s4);
        System.out.println("序號\t\t原值\t\t進制數\t\t轉換值");
        for (int i = 0; i < 50; i++) {
            String s5 = Integer.toString(num, i);
            System.out.println(i+"\t\t"+num+"\t\t"+i+"\t\t\t"+s5);
        }
    }

    private static void part4() {
        String s="100";
        Integer integer = new Integer(s);
        int i = integer.intValue();
        System.out.println(i);
        int i1 = Integer.parseInt(s);
        System.out.println(i1);
    }

    private static void part3() {
        //int-->String
        int i=1000;
        String str="";
        str=i+str;
        System.out.println(str);
        Integer integer = new Integer(i);
        System.out.println(integer.toString());
        System.out.println(String.valueOf(i));
        System.out.println(Integer.toString(i));
    }

    private static void part2() {
        Integer integer = new Integer(100);
        System.out.println(integer);
        Integer integer1 = new Integer("1000");
        System.out.println(integer1);
    }

    private static void part1() {
        int i=1231231231;
        int maxValue = Integer.MAX_VALUE;
        int minValue = Integer.MIN_VALUE;
        if (i>=minValue&&i<=maxValue) {
            System.out.println(i+"在int範圍內");
        }else {
            System.out.println(i+"超過int範圍");
        }
        System.out.println("二進制:"+Integer.toBinaryString(i));
        System.out.println("十六進制:"+Integer.toHexString(i));
        System.out.println("十進制:"+Integer.toOctalString(i));
    }
}

1.10 Character類,java.lang.Character

1.10.1 構造方法

  • Character(char value)構造一個新分配的 Character 對象,用以表示指定的 char 值。

1.10.2 成員方法

  • static boolean isUpperCase(char ch)確定指定字符是否爲大寫字母。
  • static boolean isLowerCase(char ch)確定指定字符是否爲小寫字母。
  • static boolean isDigit(char ch)確定指定字符是否爲數字。
  • static char toUpperCase(char ch)使用取自 UnicodeData 文件的大小寫映射信息將字符參數轉換爲大寫。
  • static char toLowerCase(char ch)使用取自 UnicodeData 文件的大小寫映射信息將字符參數轉換爲小寫。

1.10.3 Demo

package com.xzy.JavaUsedAPI.java.lang.Character;

public class CharacterP {
    public static void main(String[] args) {

    }

    private static void part3() {
        int big=0;
        int small=0;
        int num=0;
        String s="abcdefABCD1233";
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (Character.isUpperCase(chars[i])) {
                big++;
            }else if(Character.isLowerCase(chars[i])){
                small++;
            }else if(Character.isDigit(chars[i])){
                num++;
            }
        }
        System.out.println("big:" + big);
        System.out.println("small:" + small);
        System.out.println("big:" + num);
    }

    private static void part2() {
        boolean a = Character.isUpperCase('a');
        System.out.println(a);
        boolean b = Character.isLowerCase('b');
        System.out.println(b);
        boolean digit = Character.isDigit('9');
        System.out.println(digit);
        System.out.println(Character.toUpperCase('a'));
        System.out.println(Character.toLowerCase('A'));
    }

    private static void part1() {
        Character ch = new Character('a');
        System.out.println(ch);
        ch='b';//自動裝箱
        System.out.println(ch);
    }
}

1.11 Math類,java.lang.Math

1.11.1 成員靜態常量

  • static double E 比任何其他值都更接近 e(即自然對數的底數)的 double 值。
  • static double PI 比任何其他值都更接近 pi(即圓的周長與直徑之比)的 double 值。

1.11.2 靜態成員方法

  • static double abs(double a)返回 double 值的絕對值。
  • static double ceil(double a)返回最小的(最接近負無窮大)double 值,該值大於等於參數,並等於某個整數。
  • static double floor(double a)返回最大的(最接近正無窮大)double 值,該值小於等於參數,並等於某個整數。
  • static float max(float a, float b)返回兩個 float 值中較大的一個。
  • static double pow(double a, double b)返回第一個參數的第二個參數次冪的值。
  • static double random()返回帶正號的 double 值,該值大於等於 0.0 且小於 1.0。
  • static int round(float a)返回最接近參數的 int。
  • static double sqrt(double a)返回正確舍入的 double 值的正平方根。

1.11.3 Demo

package com.xzy.JavaUsedAPI.java.lang.Math;


import java.util.Scanner;

public class MathP {
    public static void main(String[] args) {
        part3();
    }

    private static void part3() {
        System.out.println("請輸入隨機數的起始值:");
        Scanner scanner = new Scanner(System.in);
        int start = scanner.nextInt();
        System.out.println("請輸入隨機數的終止值:");
        int end = scanner.nextInt();
        int[] arr = new int[100];
        System.out.println("序號\t\t數字");
        for (int i = 0; i < 100; i++) {
            arr[i] = (int) (Math.random() * (end - start + 1) + start);//[0,1)*200+100=[0,200)+100=[100,300)
            System.out.println(i + "\t\t" + arr[i]);
        }
    }

    private static void part2() {
        double a = -2.054888887;
        double abs = Math.abs(a);
        System.out.println(abs);
        System.out.println(Math.ceil(2.4879));
        System.out.println(Math.floor(2.4879));
        System.out.println(Math.max(2.5, 3.2));
        System.out.println(Math.pow(2, 3));
        System.out.println((int) (Math.random() * 100 + 1));
        System.out.println(Math.round(3.49));
        System.out.println(Math.sqrt(4));
    }

    private static void part1() {
        double e = Math.E;
        System.out.println(e);
        double pi = Math.PI;
        System.out.println(pi);
    }
}

1.12 Random類,java.util.Random

1.12.1 構造方法

  • Random()創建一個新的隨機數生成器。種子是當前時間的毫秒值
  • Random(long seed)使用單個 long 種子創建一個新的隨機數生成器。 使用seed種子生產隨機數

1.12.2 成員方法

  • int nextInt()返回下一個僞隨機數,它是此隨機數生成器的序列中均勻分佈的 int 值。
  • void setSeed(long seed)使用單個 long 種子設置此隨機數生成器的種子。

1.12.3 Demo

package com.xzy.JavaUsedAPI.java.util.Random;

import java.util.Random;
import java.util.Scanner;

public class RandomP {
    public static void main(String[] args) {

    }

    private static void part1() {
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int i1 = random.nextInt();
            System.out.println(i1);
        }
        System.out.println();
        for (int i = 0; i < 10; i++) {
            System.out.println(random.nextInt());
        }
        for (int i = 0; i < 1000; i++) {
            System.out.print(random.nextInt(100)+1+",");//[0,100)
        }
    }
    private static void part2() {
        Random random = new Random();
        System.out.println("請輸入隨機數的起始值:");
        Scanner scanner = new Scanner(System.in);
        int start = scanner.nextInt();
        System.out.println("請輸入隨機數的終止值:");
        int end = scanner.nextInt();
        int[] arr = new int[100];
        System.out.println("序號\t\t數字");
        for (int i = 0; i < 100; i++) {
            arr[i] = (int) (random.nextInt(end-start+1)+start);//[0,1)*200+100=[0,200)+100=[100,300)
            System.out.println(i + "\t\t" + arr[i]);
        }
    }
}

1.13 System類,java.lang.System

1.13.1 靜態方法

  • static PrintStream err “標準”錯誤輸出流。
  • static InputStream in “標準”輸入流。
  • static PrintStream out “標準”輸出流。

1.13.2 成員方法

  • static void gc()運行垃圾回收器。
    • System.gc()可用於垃圾回收。當使用System.gc()回收某個對象所佔用的內存之前,通過要求程序調用適當的方法來 清理資源。在沒有明確指定資源清理的情況下,
    • Java提高了默認機制來清理該對象的資源,就是調用Object類的finallize()方法。finalize()方法的作用是釋放一個對象佔用的內存空間時,會被JVM調用。
    • 而子類重寫該方法,就可以清理對象佔用的資源,該方法沒有鏈式調用,所以必須手動實現。
    • 從程序的運行結果可以發現,執行System.gc()前,系統會自動調用finallize()方法清除對象佔有的資源,通過super.finalize()方式可以實現從下到上finalize()方法的調用,即先釋放自己的資源,再去釋放父類的資源。
    • 但是,不要在程序中頻繁的調用垃圾回收,因爲每一次執行垃圾回收,jvm都會強制啓動垃圾回收器運行,這會耗費更多的系統資源,會與正常的Java 程序運行爭搶資源,
    • 只有在執行大量的對象的釋放,才能調用垃圾回收最好。
  • static void exit(int status)終止當前正在運行的 Java 虛擬機。
    0正常終止程序,非0非正常終止程序
  • static long currentTimeMillis()返回以毫秒爲單位的當前時間。
  • static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)從指定源數組中複製一個數組,複製從指定的位置開始,到目標數組的指定位置結束。

1.13.3 Demo

package com.xzy.JavaUsedAPI.java.lang.System;

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

    public Student() {
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    @Override
    protected void finalize() throws Throwable {
        System.out.println("父類資源清理");
        super.finalize();
    }
}

package com.xzy.JavaUsedAPI.java.lang.System;

import java.util.Arrays;

public class SystemP {
    public static void main(String[] args) {

    }

    private static void part3() {
        System.out.println(System.currentTimeMillis());
        int[] arr1={1,2,3,4,5,6};
        int[] arr2={6,7,8,9,10};
        System.out.println(Arrays.toString(arr2));
        System.arraycopy(arr1,2,arr2,0,2);
        System.out.println(Arrays.toString(arr2));
    }

    private static void part2() {
        System.out.println("程序將退出");
        System.exit(0);
    }

    private static void part1() {
        Student xzy = new Student("xzy", 20);
        xzy=null;
        System.gc();
    }
}

1.14 BigInteger類,java.math.BigInteger

1.14.1 構造方法

  • BigInteger(String val)將BigInteger的十進制字符串表示形式轉換爲BigInteger。

1.14.2 成員方法

  • BigInteger add(BigInteger val)返回其值爲(this + val)的BigInteger。
  • BigInteger subtract(BigInteger val)返回其值爲(this - val)的BigInteger。
  • BigInteger multiply(BigInteger val)返回其值爲(this * val)的BigInteger。
  • BigInteger divide(BigInteger val)返回其值爲(this / val)的BigInteger。
  • BigInteger[] divideAndRemainder(BigInteger val)返回包含(this / val)後跟(this % val)的兩個BigInteger的數組。

1.14.3 Demo

package com.xzy.JavaUsedAPI.java.math.BigInteger;


import java.math.BigInteger;

public class BigIntegerP {
    public static void main(String[] args) {

    }

    private static void part3() {
        BigInteger bigInteger = new BigInteger("10");
        BigInteger bigInteger1 = new BigInteger("20");
        BigInteger add = bigInteger.add(bigInteger1);
        System.out.println(add);
        BigInteger subtract = bigInteger.subtract(bigInteger1);
        System.out.println(subtract);
        BigInteger multiply = bigInteger.multiply(bigInteger1);
        System.out.println(multiply);
        BigInteger divide = bigInteger.divide(bigInteger1);
        System.out.println(divide);
        BigInteger[] bigIntegers = bigInteger.divideAndRemainder(bigInteger1);
        System.out.println("----");
        for (BigInteger integer : bigIntegers) {
            System.out.println(integer);
        }
    }

    private static void part2() {
        BigInteger bigInteger = new BigInteger("214748364812121212");
        System.out.println(bigInteger);
    }

    private static void part1() {
        int maxValue = Integer.MAX_VALUE;
        int minValue = Integer.MIN_VALUE;
        System.out.println(maxValue);//2147483647
        System.out.println(minValue);//-2147483648
        Integer integer = new Integer(maxValue+1);//-2147483648
        //Integer integer1 = new Integer("2147483648");//java.lang.NumberFormatException: For input string: "21474836481
        //System.out.println(integer1);
        System.out.println(integer);
    }
}

1.15 BigDecimal類,java.math.BigDecimal類

1.15.1 靜態方法

  • static int ROUND_CEILING接近正無窮大的舍入模式。 向上取整
  • static int ROUND_FLOOR接近負無窮大的舍入模式。 向下取整
  • static int ROUND_HALF_UP向“最接近的”數字舍入,如果與兩個相鄰數字的距離相等,則爲向上舍入的舍入模式。四捨五入

1.15.2 構造方法

  • BigDecimal(BigInteger val)將BigInteger轉換爲BigDecimal。

1.15.3 成員方法

  • BigDecimal add(BigDecimal augend)返回一個 BigDecimal,其值爲 (this + augend),其標度爲 max(this.scale(), augend.scale())。
  • BigDecimal subtract(BigDecimal subtrahend)返回一個 BigDecimal,其值爲 (this - subtrahend),其標度爲 max(this.scale(), subtrahend.scale())。
  • BigDecimal multiply(BigDecimal multiplicand)返回一個 BigDecimal,其值爲 (this × multiplicand),其標度爲 (this.scale() + multiplicand.scale())。
  • BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)返回一個 BigDecimal,其值爲 (this / divisor),其標度爲指定標度。

1.15.4 Demo

package com.xzy.JavaUsedAPI.java.math.BigDecimal;

import java.math.BigDecimal;

public class BigDecimalP {
    public static void main(String[] args) {
        
    }

    private static void part1() {
        BigDecimal bigDecimal = new BigDecimal("0.999");
        BigDecimal bigDecimal1 = new BigDecimal("1.22355554888");
        BigDecimal add = bigDecimal.add(bigDecimal1);
        System.out.println(add);
        BigDecimal subtract = bigDecimal.subtract(bigDecimal1);
        System.out.println(subtract);
        BigDecimal multiply = bigDecimal.multiply(bigDecimal1);
        System.out.println(multiply);
        BigDecimal divide1 = bigDecimal.divide(new BigDecimal("2"), 3, BigDecimal.ROUND_HALF_UP);
        BigDecimal divide2 = bigDecimal.divide(new BigDecimal("2"), 8, BigDecimal.ROUND_HALF_UP);
        BigDecimal divide3 = bigDecimal.divide(new BigDecimal("2"), 3, BigDecimal.ROUND_CEILING);
        BigDecimal divide4 = bigDecimal.divide(new BigDecimal("2"), 3, BigDecimal.ROUND_FLOOR);
        System.out.println(divide1);
        System.out.println(divide2);
        System.out.println(divide3);
        System.out.println(divide4);
    }
}

1.16 Date類,java.util.Date

1.16.1 構造方法

  • Date()分配 Date 對象並初始化此對象,以表示分配它的時間(精確到毫秒)。
  • Date(long date)分配 Date 對象並初始化此對象,以表示自從標準基準時間(稱爲“曆元(epoch)”,即 1970 年 1 月 1 日 00:00:00 GMT)以來的指定毫秒數。

1.16.2 成員方法

  • long getTime()返回自 1970 年 1 月 1 日 00:00:00 GMT 以來此 Date 對象表示的毫秒數。
  • void setTime(long time)設置此 Date 對象,以表示 1970 年 1 月 1 日 00:00:00 GMT 以後 time 毫秒的時間點。

1.16.3 Demo

package com.xzy.JavaUsedAPI.java.util.Date;

import java.util.Date;

public class DateP {
    public static void main(String[] args) {

    }

    private static void part2() {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            System.out.println(i);
        }
        long end = System.currentTimeMillis();
        long time = end - start;
        System.out.println(time);
    }

    private static void part1() {
        Date date = new Date();
        System.out.println(date.toLocaleString());
        Date date1 = new Date(1000);
        System.out.println(date1.toLocaleString());
        System.out.println(date.getTime());
        System.out.println(date1.getTime());
        date.setTime(100000);
        System.out.println(date.toLocaleString());
        long l = System.currentTimeMillis();
        System.out.println(l);
        System.out.println(new Date(l).toLocaleString());
    }
}

1.17 DateFormat類,java.text.DateFormat

1.17.1 構造方法

  • protected DateFormat()創建一個新的 DateFormat。

1.17.2 成員方法

  • Date parse(String source)從給定字符串的開始解析文本,以生成一個日期。
  • String format(Date date)將一個 Date 格式化爲日期/時間字符串。

1.17.3 Demo

package com.xzy.JavaUsedAPI.java.text.DateFormat;

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

public class DateUtils {
    private DateUtils(){}
    public static String getDate(String str) throws ParseException {
        String pattern="yyyy年MM月dd日HH:mm:ss";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        String parse = simpleDateFormat.parse(str).toLocaleString();
        return parse;
    }
    public static String getDate(String str,String pattern) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        String parse = simpleDateFormat.parse(str).toLocaleString();
        return parse;
    }
    public static String getString(Date date){
        String pattern="yyyy年MM月dd日HH時mm分ss秒";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        String format = simpleDateFormat.format(date);
        return format;
    }
    public static String getString(Date date,String pattern){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        String format = simpleDateFormat.format(date);
        return format;
    }
}

package com.xzy.JavaUsedAPI.java.text.DateFormat;

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

public class DateFormatP {
    public static void main(String[] args) throws ParseException {

    }

    private static void part4() throws ParseException {
        System.out.println("請輸入你的生日:");
        Scanner scanner = new Scanner(System.in);
        String birthday = scanner.nextLine();
        SimpleDateFormat date = new SimpleDateFormat("yyyy年MM月dd日");
        Date parse = date.parse(birthday);
        long time = parse.getTime();
        long currentTimeMillis = System.currentTimeMillis();
        long l = currentTimeMillis - time;
        long i = l / 1000 / 60 / 60 / 24;
        System.out.println(i);
    }

    private static void part3() throws ParseException {
        //工具類調用
        System.out.println(DateUtils.getDate("2020年5月19日20:43:19"));
        System.out.println(DateUtils.getString(new Date()));
        System.out.println("請輸入你的生日:");
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        String birthday = DateUtils.getDate(s, "yyyy年MM月dd日");
        System.out.println(birthday);

    }

    private static void part2() throws ParseException {
        String str="2020年5月19日20:12:20";
        String pattern="yyyy年MM月dd日HH:mm:ss";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        System.out.println(simpleDateFormat.parse(str).toLocaleString());
    }

    private static void part1() {

        String pattern="yyyy年MM月dd日HH時mm分ss秒";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Date date = new Date();
        String format = simpleDateFormat.format(date);
        System.out.println(format);
    }
}

1.18 Calendar類,java.util.Calendar

1.18.1 構造方法

  • protected Calendar()構造一個帶有默認時區和語言環境的 Calendar。
  • protected Calendar(TimeZone zone, Locale aLocale)構造一個帶有指定時區和語言環境的 Calendar。

1.18.2 成員方法

  • static Calendar getInstance()使用默認時區和語言環境獲得一個日曆。
  • int get(int field)返回給定日曆字段的值。
  • Date getTime()返回一個表示此 Calendar 時間值(從曆元至現在的毫秒偏移量)的 Date 對象。
  • long getTimeInMillis()返回此 Calendar 的時間值,以毫秒爲單位。
  • abstract void add(int field, int amount)根據日曆的規則,爲給定的日曆字段添加或減去指定的時間量。
  • void set(int year, int month, int date)設置日曆字段 YEAR、MONTH 和 DAY_OF_MONTH 的值。

1.18.3 Demo

package com.xzy.JavaUsedAPI.java.util.Calender;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

public class CalenderP {
    public static void main(String[] args) {

    }

    private static void part4() {
        Calendar in = Calendar.getInstance();
        System.out.println("請輸入一個年份:");
        Scanner scanner = new Scanner(System.in);
        int date = scanner.nextInt();
        in.set(Calendar.YEAR,date);
        in.set(Calendar.MONTH,2);
        in.set(Calendar.DAY_OF_MONTH,1);
        in.add(Calendar.DAY_OF_MONTH,-1);
        int i = in.get(Calendar.DAY_OF_MONTH);
        System.out.println(i);
    }

    private static void part3() {
        Calendar in = Calendar.getInstance();
        in.set(Calendar.YEAR,2010);
        in.add(Calendar.YEAR,5);
        in.add(Calendar.YEAR,-10);
        Date time = in.getTime();
        System.out.println(time.toLocaleString());
    }

    private static void part2() {
        Calendar ca = Calendar.getInstance();
        Date time = ca.getTime();
        System.out.println(time.toLocaleString());
        System.out.println(ca.getTimeInMillis());
    }

    private static void part1() {
        Calendar instance = Calendar.getInstance();
        ArrayList<Integer> in = new ArrayList<>();
        in.add(instance.get(Calendar.YEAR));
        in.add(instance.get(Calendar.MONTH));
        in.add(instance.get(Calendar.DAY_OF_MONTH));
        in.add(instance.get(Calendar.HOUR));
        in.add(instance.get(Calendar.MINUTE));
        in.add(instance.get(Calendar.SECOND));
        in.add(instance.get(Calendar.WEEK_OF_MONTH));
        in.add(instance.get(Calendar.DAY_OF_WEEK));
        for (Integer integer : in) {
            System.out.println(integer);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章