Java 常用API


 

常用api第一部分

String 類

雙引號字符串,都是 String 類的對象

字符串的特點:

  1. 字符串的內容永不可變(正是因為字符串不可改變,所以字符串是可以共享使用的)
  2. 字符串效果上相當於是 char[] 字符數組,但是底層原理是 byte[] 字節數組

 

字符串的常見的 3 + 1 種創建方式

public class DemoString {
    public static void main(String[] args) {
        // 最簡單的方式創建一個字符串
        String str = "johny";

        // 使用空參構建
        String str1 = new String();
        System.out.println(str1);  // ""
        
        // 根據字符數組的內容,來創建對應的字符串
        char[] charArray = {'A', 'B', 'C'};
        String str2 = new String(charArray);
        System.out.println(str2);  // "ABC"

        // 根據字節數組的內容,來創建對應的字符串
        byte[] byteArray = {97, 98, 99};
        String str3 = new String(byteArray);
        System.out.println(str3);  // "abc"
    }
}

 

字符串常量池

 

字符串的比較

  • == 運算符是進行地址值的比較,比較字符串內容,可使用 equals() 方法;(python 中 == 是比較內容,is 是比較地址值)
  • equals() 具有對稱性,也就是 a.equals(b)  和  b.equals(a)  是一樣的
  • 如果是一個常量與一個變量比較,推薦把常量寫在前面:"abc".equals(a),因為前面的字符串不能是null,否則會出現 NullPointerException 異常
  • equalsIgnoreCase()  方法在比較時忽略大小寫
public class StringEquals {
    public static void main(String[] args) {
        String strA = "abc";
        String strB = "abc";

        char[] arrayChar = {'a', 'b', 'c'};
        String strC = new String(arrayChar);

        System.out.println(strA.equals(strB));  // true
        System.out.println(strA.equals(strC));  // true

        // 推薦寫法
        System.out.println("abc".equals(strA));  // true

        // 空指針異常
        String strD = null;
        // System.out.println(strD.equals(strA));  // NullPointerException

        // equalsIgnoreCase()
        System.out.println("ABC".equalsIgnoreCase(strA));  // true
    }
}

 

字符串常用方法

  • int  length():獲取字符串長度
  • String  concat(String str):將當前字符串和參數字符串進行拼接
  • char  charAt(int index):獲取指定索引值位置的字符
  • int  indexOf(String/char  args):查找參數字符串/字符在當前字符串中的第一次索引位置,如果沒有找到就返回 -1
public class StringGet {
    public static void main(String[] args) {
        String strA = "abc";

        char[] arrayChar = {'A', 'B', 'C'};
        String strB = "ABC";

        // 返回字符串長度
        System.out.println(strA.length());  // 3

        // 字符串拼接
        System.out.println(strA.concat(strB));  // abcABC

        // 返回指定索引值位置上的字符
        System.out.println(strA.charAt(1));  // b

        // 查找參數字符串在當前字符串中的第一次索引位置,沒有找到就返回-1
        System.out.println(strA.indexOf("bc"));  // 1
        System.out.println(strA.indexOf("d"));  // -1
    }
}

 

字符串的截取(切片)

  • String substring(int index):截取從參數位置一直到字符串末尾,返回新字符串
  • String substring(int begin,  int end):截取從 begin 開始,到 end 結束,顧前不顧尾(不能添加步長參數,python可以)
public class StringSubstring{
    public static void main(String[] args){
        String strA = "hello, world!";
        
        // 截取
        System.out.println(strA.substring(0, 5));  // hello
    }
}

 

字符串轉換

  • char[]  toCharArray():將字符串拆分成字符數組,返回該字符數組
  • byte[]  getBytes():獲取字符串底層字節數組,返回該字節數組的地址值(引用對象)
  • String  replace(CharSequence oldString,  CharSequence newString):將出現的所有老字符串替換成新字符串,返回替換后的結果字符串
public class StringConvert{
    public static void main(String[] args){
        String strA = "中國";

        // 返回字符數組
        System.out.println(strA.toCharArray());  // 中國

        // 返回字節數組(返回的是對象的引用)
        byte[] byteArray1 = strA.getBytes();
        System.out.println(byteArray1);  // [B@1e643faf
        for (int i = 0; i < strA.length(); i++){
            System.out.print(byteArray1[i]);  // -28-72
            if (i == strA.length() - 1){
                System.out.println();
            }
        }

        byte[] byteArray2 = "abc".getBytes();
        System.out.println(byteArray2);  // [B@6e8dacdf
        for (int i = 0; i < "abc".length(); i++){
            System.out.print(byteArray2[i]);  // 979899
            if (i == "abc".length() - 1){
                System.out.println();
            }
        }

        // 字符串替換
        System.out.println(strA.replace("中", "愛"));  // 愛國
    }
}

 

字符串的切割

  • String[]  split(String regex):按照參數規則,將當前字符串分割成多個部分,返回字符串數組的地址值(引用對象)
  • split() 方法的參數其實是一個正則表達式,如果按照英文句點 . 進行切分,必須寫 \\.(雙斜線 + 點)
public class StringSplit {
    public static void main(String[] args) {
        String strA = "my name is johny";
        String[] Array1 = strA.split(" ");

        System.out.println(Array1);  // [Ljava.lang.String;@1b6d3586
        for (int i=0; i < Array1.length; i++){
            System.out.println(Array1[i]);  // my \n name \n is \n johny
        }

        // 特殊寫法
        String strB = "a.b.c";
        String[] Array2 = strB.split("\\.");

        System.out.println(Array2);  // [Ljava.lang.String;@4554617c
        for (int i = 0; i < Array2.length; i++){
            System.out.println(Array2[i]);  // a \n b \n c
        }
    }
}

 

Scanner 類

Scanner 類可以實現鍵盤輸入,類似於 python 中的 input,不過通過 input 接收到的都是 str,但 Scanner 對象可以生成指定類型

Scanner 是引用數據類型,需要導入 Scanner 類,(為什么 String 類不需要導入?因為只有 java.lang 包下的內容不需要導包)

import java.util.Scanner;

public class DemoScanner {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 讓用戶輸入一個整數,用戶輸入的不是整數會拋出異常(InputMismatchException)
        int num = scanner.nextInt();
        // 輸入一個字符串
        String str = scanner.next();
        System.out.println(num + str);
    }
}

 

匿名對象

匿名對象就是只有 右邊的對象,沒有左邊的命名和賦值運算符;匿名對象只能使用唯一的一次,下次再用,不得不再 new 一個

new  類名稱();

import java.util.Scanner;

public class Anonymous {
    public static void main(String[] args) {
        // Scanner 匿名對象
        int num = new Scanner(System.in).nextInt();
        System.out.println(num);
        // 匿名對象當做參數傳遞
        showNum(new Scanner(System.in));
    }

    public static void showNum(Scanner scanner){
        System.out.println(scanner.next());
    }
}

 

Random 類

Random 類可用來生成一個隨機數;Random  random  =  new  Random()

獲取一個隨機 int 數字(默認是 int 所有范圍,有正負兩種):int num = random.nextInt();

獲取一個隨機 int 數字(指定范圍 [0, 99),規則是顧前不顧尾):int num = random.nextInt(100);

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

public class RandomGames {
    public static void main(String[] args) {
        int num = new Random().nextInt(100);
        guess(num);
    }
    public static void guess(int num){
        while (true){
            int input_num = new Scanner(System.in).nextInt();
            if (input_num > num){
                System.out.println("greater than");
            }
            else if(input_num < num){
                System.out.println("less than");
            }
            else{
                System.out.println("bingo~");
                break;
            }
        }
    }
}

 

ArrayList 類

ArrayList 類是 Array 的子類,它的長度可變,元素類型是統一的

有一個尖括號代表泛型(就是裝在 ArrayList 中的元素的類型),泛型只能引用類型

直接打印 ArrayList,看到的不是地址值(Array是地址值),而是存儲內容,如果內容為空,那么打印 []

import java.util.ArrayList;

public class DemoArrayList {
    public static void main(String[] args) {
        // 創建一個ArrayList
        ArrayList<String> arrayList = new ArrayList<>();

        arrayList.add("甲");
        // arrayList.add(10);   // 泛型已經指明是String類型,況且只能是引用類型
        System.out.println(arrayList);  // [甲]
    }
}

 

ArrayList 的常用方法

public  boolean  add(E  e):添加元素,元素 e 應和 泛型 E 一致,返回值是 boolean 類型

public  E  get(int  index):根據索引值取出元素,返回元素類型與泛型一致

public  E  remove(int  index):根據索引值刪除元素,返回元素類型與泛型一致

public  int  size():獲取長度,返回 int 類型

 

demo_01:

import java.util.ArrayList;

public class ArrayListMethod {
    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList();

        // 添加
        boolean bool = arrayList.add("甲");
        System.out.println(bool);  // true

        // 獲取
        String str = arrayList.get(0);
        System.out.println(str);  //// 獲取大小
        int count = arrayList.size();
        System.out.println(count);  // 1

        // 刪除
        String delete = arrayList.remove(0);
        System.out.println(delete);  //
    }
}

demo_02:

// 定義以指定格式打印集合的方法,格式參照:{元素@元素@元素@元素}
import java.util.ArrayList;

public class ArrayListPrint {
    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<>();

        arrayList.add("2019");
        arrayList.add("-02");
        arrayList.add("-14");
        System.out.println(arrayList);  // [2019, -02, -14]

        arrayListPrint(arrayList);
    }

    public static void arrayListPrint(ArrayList<String> arrayList){
        System.out.print("{");
        for (int i = 0; i < arrayList.size(); i++){
            String str = arrayList.get(i);
            System.out.print(str);
            if (i != arrayList.size() - 1){
                System.out.print("@");
            }
        }
        System.out.print("}"); // {2019@-02@-14}
    }
}

 

如果說需要往 ArrayList 中存儲基本數據類型,那么可以使用基本數據類型對應的包裝類

包裝類與 String 類一樣,都在 java.long 包下,所以可以直接使用

Byte --> byte  

Short --> short  

Integer --> int  

Long --> long  

Float --> float  

Double --> double  

Character --> char  

Boolean --> boolean

從 JDK 1.5 開始, 支持自動裝箱, 自動拆箱: 基本類型 --> 包裝類

import java.util.ArrayList;

public class WrapperClass {
    public static void main(String[] args) {
        // 指定集合中的泛型是Integer
        ArrayList<Integer> arrayList = new ArrayList<>();

        arrayList.add(100);
        int num = arrayList.get(0);
        System.out.println(num);  // 100
    }
}

 

包裝類成員方法: 

  • valueOf() 裝箱
  • intValue() 拆箱
public class Main {
    public static void main(String[] args) {
        // 裝箱
        // Integer ig = new Integer("123456");
        Integer ig = Integer.valueOf("123456");
        // 拆箱
        int i = ig.intValue();
        System.out.println(i);   // 123456

        // 自動裝箱, 拆箱
        Integer ig2 = 123456;
        int i2 = ig2;
    }
}

 

數組工具類 Arrays

java.util.Arrays 類是一個與數組相關的工具類,里面提供了大量靜態方法,用來實現常見的數組操作

public  static  String  toString(參數數組):將參數數組轉換為字符串返回(按照默認格式:[element1, element2, element3 …])

public  static  void  sort(參數數組):將當前數組進行排序,默認升序

import java.util.Arrays;

public class DemoArrays {
    public static void main(String[] args) {
        int[] arrayNum = {5, 1, 6, 3, 9};
        String[] arrayString = {"bbb", "ccc", "aaa"};

        // toString()
        System.out.println(Arrays.toString(arrayNum));  // [5, 1, 6, 3, 9]

        // sort()
        Arrays.sort(arrayNum);
        System.out.println(Arrays.toString(arrayNum));  // [1, 3, 5, 6, 9]
        Arrays.sort(arrayString);
        System.out.println(Arrays.toString(arrayString));  // [aaa, bbb, ccc]
    }
}

 

數學工具類 Math

java.util.Math 類是數學相關的工具類,里面提供了大量的靜態方法,完成數學運算相關的操作

  1. public  static  double  abs(double  num):獲取絕對值
  2. public  static  double  ceil(double  num):向上取整
  3. public  static  double  floor(double  num):向下取整
  4. public  static  long  round(double  num):四舍五入
    public class DemoMath {
        public static void main(String[] args) {
            double num = -12.24;
    
            // 絕對值
            System.out.println(Math.abs(num));  // 12.24  double
    
            // 向上取整
            System.out.println(Math.ceil(num));  // 12.0  double
    
            // 向下取整
            System.out.println(Math.floor(num));  // 13.0  double
    
            // 四舍五入
            System.out.println(Math.round(num));  // 12  long
        }  
    }

     

靜態 static 關鍵字

static 關鍵字概述

 

static 修飾成員變量(修飾后類似於類屬性)

如果一個成員變量使用了 static 關鍵字,那么這個成員變量不再屬於自己,而是屬於所在的類,多個對象共享這個變量    

推薦寫法:類名.變量名

// 這里少了一個例子

 

static 修飾成員方法(修飾后類似於類方法)

如果沒有 static 關鍵字,那么必須創建對象,然后通過對象來調用方法

對於靜態方法來說,可以通過對象名進行調用,也可以直接通過類名稱進行調用(推薦);使用對象名調用時,會被javac翻譯成:類名.方法名

注意事項:

  1. 靜態不能直接訪問非靜態(因為在內存中是先有的靜態內容,后有的非靜態內容)
  2. 靜態方法中不能使用 this
    public class StaticMethod{
        private int num;
        static int staticNum;
    
        // 實例方法
        public void method(){
            System.out.println("this is obj method");
            // 非靜態可以訪問靜態
            System.out.println(staticNum);  // 0
        }
    
        // 類方法
        public static void classMethod(){
            System.out.println("this is class method");
            // 靜態不能訪問非靜態
            // System.out.println(num);
        }
    
        public static void main(String[] args){
            // 使用類名調用類方法
            StaticMethod.classMethod();
            // 使用對象調用實例方法
            StaticMethod sm = new StaticMethod();
            sm.method();
        }
    }

     

靜態代碼塊(用來一次性的對類變量進行賦值)

注意事項:

  1. 當第一次用到當前類時,靜態代碼塊執行唯一的一次
  2. 靜態內容總是優先於非靜態,所以靜態代碼塊比構造方法先執行
    public class StaticCodeBlock{
        static{
            // 靜態代碼塊
            System.out.println("static code block execution");
        }
    
        // 構造方法
        public StaticCodeBlock(){
            System.out.println("constructor execution");
        }
    
        public static void main(String[] args) {
            StaticCodeBlock codeOne = new StaticCodeBlock();
            StaticCodeBlock codeTwo = new StaticCodeBlock();
        }
    }
    // 執行結果
    // static code block execution  // 執行唯一一次
    // constructor execution
    // constructor execution

 

 

ending ~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM