Java基礎(4):Java常見API

1 API

  • Application Program Interface(應用程序接口),是JDK中提供的可以使用的類。
  • jdk的安裝目錄下有個src.zip文件,其存放的就是所有java類的源文件。
  • 可以在官網在線查詢各種API。

2 Object類

  • Object類是Java中的根類,即所有類、數組的父類。(接口除外)
  • Object類常用方法
    注意:可繼承且不是final修飾的方法,都可以通過重寫方法實現需要的功能。
Modifier and Type Method Description
public boolean equals​(Object obj) 判斷指定對象與該對象是否相等(內存地址)
public String toString() 返回對象的字符串表示
protected void finalize() 垃圾回收
public native int hashCode() 返回對象的hashCode值
public final native Class<?> getClass() 返回對象的運行時類
equals方法
  • 子類可通過重寫方法實現需要的功能。
    public class Person{
        ...
        //Override equals()方法
        public boolean equals(Object obj){
            if(this == obj){                    //同一對象
                return true;
            }
            if(obj instanceof Person){          //同類才能比較,保證可以強制類型轉換
                Person person = (Person)obj;    //強制類型轉換
                return this.name==person.name;
            }
            return false;
        }
    }
    
toString方法
  • 注意:輸出語句中,輸出對象會默認調用對象的toString方法。
    Person p = new Person();
    System.out.println(p);
    System.out.println(p.toString());    //兩句輸出結果一樣
    

3 與用戶互動

3.1 運行Java程序的參數

  Java程序的入口——main(String[] args)方法中參數可通過命令行指定。

  • 命令:java 文件名 參數值
    public class ArgsTest{
        public static void main(String[] args){
            // 輸出args數組長度
            System.out.println(args.length);
            // 遍歷args數組元素
            for(String arg : args){
                System.out.println(arg);
            }
        }
    }
    

3.2 Scanner類

  • Scanner類是基於正則表達式的文本掃描器。
  • 從文件、輸入流、字符串中解析出基本類型值和字符串值。
  • Scanner類常用方法
Modifier and Type Method Description
public Scanner(InputStream source) 構造器1,接收輸入流
public Scanner(File source) 構造器2,接收文件
public boolean hasNextXxx() 判斷是否還有下一個輸入項
public Xxx nextXxx() 獲取下一個輸入項
public Scanner useDelimiter(Pattern pattern) 設置特定輸入分隔符

注意

  1. Xxx不存在時表示字符串String。
  2. 默認情況下,Scanner使用空白(包括空格、Tab空白、回車)作爲輸入分隔符。

4 系統相關

4.1 System類

  • System類代表程序所在系統。
  • System類的構造方法被private修飾,不能創建System類對象
  • System類中方法都是static方法,類名直接訪問即可。
  • System類變量
Modifier and Type Field Description
public final static InputStream in 標準輸入流
public final static PrintStream out 標準輸出流
public final static PrintStream err 標準錯誤輸出流
  • System類常用方法
Modifier and Type Method Description
static long currentTimeMillis() 返回當前日期的毫秒值
public static void gc() 垃圾回收
public static Map<String,String> getenv() 獲取系統環境變量
public static Properties getProperties() 獲取系統屬性

4.2 Runtime類

  • Runtime類代表程序的運行時環境。
  • Runtime類的構造方法與System類似,不能new創建對象,可用getRuntime()方法創建對象。
  • Runtime類常用方法
Modifier and Type Method Description
public static Runtime getRuntime() 獲得與程序關聯的Runtime對象
public native void gc() 垃圾回收
public Process exec(String command) 啓動進程運行操作系統的命令

5 字符串類

5.1 String類

  • Java中描述字符串的類。
  • 字符串是String類常量對象(本質是字符數組: private final char value[];),但String類的引用變量可以指向不同字符串常量。
  • String類常用方法
    • 構造器
Modifier and Type Method Description
public String(String original) 構造器1
public String(char value[]) 構造器2,將字符數組轉化爲字符串,不查詢編碼表。
public String(byte bytes[]) 構造器3,通過平臺(OS)的默認字符集(GBK)解碼指定的byte數組,構造新的String。
  • 其他方法
Modifier and Type Method Description
public int length() 返回字符串長度
public String substring(int beginIndex) 返回字符串的一部分
public char charAt(int index) 返回字符串第index個字符
public String toLowerCase() 返回全小寫的字符串
public int indexOf(String str) 返回str第一次出現的位置
  • 正則表達式相關方法
Modifier and Type Method Description
public boolean matches(String regex) 匹配
public String[] split(String regex) 切割
public String replaceAll(String regex, String replacement) 替換

注意

  1. matches方法要從頭到尾全匹配才返回true,原因是其方法本質是matches("^yourregex$")
  2. Java字符串中反斜槓(\)本身需要轉義,因此兩個反斜槓(\\)實際上相當於一個,如轉義字符\d在Java中需要表示爲\\d.
  3. 正則表達式內容參考這裏

5.2 StringBuffer類

  • 字符串緩衝區,支持可變的字符串,提高字符串操作效率。
  • 採用可變數組實現char value[];
  • 線程安全類,保持同步,單線程情況下可用StringBuilder類代替。
  • 常用方法
Modifier and Type Method Description
public synchronized StringBuffer append(String str) 添加字符串
public synchronized StringBuffer insert(int offset, String str) 在offset位置插入
public synchronized StringBuffer reverse() 字符串反轉
public synchronized StringBuffer delete(int start, int end) 刪除
  • 如使用append方法,效率比String對象的+=高:
    public static void main(String[] args) {
        int[] data=new int[] {1,2,3,4};
        System.out.println(intToString(data));  //打印結果:[1,2,3,4]
    }
    public static String intToString(int[] arr){
    StringBuffer buffer = new StringBuffer();
        buffer.append("[");
        for(int i=0;i<data.length;i++) {
            if(i==data.length-1) {
                buffer.append(data[i]).append("]");
    	}else {
    	    buffer.append(data[i]).append(",");
    	}
        }
        return buffer.toString();
    }
    

5.3 StringBuilder類

  • StringBuilder和StringBuffer基本類似,區別在於StringBuffer是線程安全的,而StringBuilder不是。

6 正則表達式相關類

6.1 Pattern類

  • Pattern對象是正則表達式編譯後在內存中的表現形式。
編譯
regex
Pattern對象
  • Pattern對象由static方法compile()獲得。
  • Pattern類常用方法
Modifier and Type Method Description
public static Pattern compile(String regex) 編譯regex存到Pattern對象
public static boolean matches(String regex, CharSequence input) 直接匹配
public Matcher matcher(CharSequence input) 創建Matcher對象
//字符串編譯爲Pattern對象
Pattern p = Pattern.compile("(?=.*[0-9a-zA-Z])[!-~]{8,16}");
//使用Pattern對象創建Matcher對象
Matcher matcher = p.matcher(".12345678");
//判斷是否匹配
boolean b = matcher.matches();

上面3步等價於:

boolean b = Pattern.matches("(?=.*[0-9a-zA-Z])[!-~]{8,16}",".12345678");

6.2 Matcher類

  • 解釋Pattern對字符序列進行匹配。
  • Matcher類沒有默認構造器,只能通過Pattern對象的matcher()方法獲得Matcher類對象。
  • Matcher類常用方法:
Modifier and Type Method Description
public boolean matches() 返回整個字符串與Pattern是否匹配
public boolean find() 返回字符串是否包含與Pattern匹配的子串
public String group() 返回上一次與Pattern匹配的子串
public Matcher reset(CharSequence input) 將該Matcher對象用於新的字符序列
Pattern p = Pattern.compile("(?=.*[0-9a-zA-Z])[!-~]{8,16}");
Matcher matcher = p.matcher(".123456789abcdef12345678");
boolean b = matcher.matches(); //是否完全匹配
boolean c = matcher.find();  //是否有子串匹配
System.out.println(b);  //輸出false
System.out.println(c);  //輸出true
System.out.println(matcher.group());  //輸出上一次匹配子串:12345678

注意:find()和group()方法可以從目標字符串中依次取出特定字符串。

Pattern p = Pattern.compile("(?=.*[0-9a-zA-Z])[!-~]{8,16}");
Matcher matcher = p.matcher(".123456789abcdef12345678");
while(matcher.find()) {
	System.out.println(matcher.group());  //依次輸出:.123456789abcdef 和 12345678
}

7 數學相關類

7.1 Math類

  • 構造器被定義成private,不能創建對象。
  • Math方法全是靜態方法,由類直接調用。
  • Math類變量
Modifier and Type Field Description
public static final double PI 圓周率3.14159265358979323846
public static final double E 自然對數2.7182818284590452354
  • Math類常用方法
Modifier and Type Method Description
public static int abs(Xxx a) 返回a的絕對值
public static int round(double a) 四捨五入取整
public static double sqrt(double a) 計算平方根
public static double pow(double a, double b) 計算ab
public static double sin(double a) 計算正弦值
public static double asin(double a) 反正弦值

7.2 Random類

  • 用於生成僞隨機數
  • 構造器
Modifier and Type Method Description
public Random() 當前時間爲種子生成隨機數
public Random(long seed) 顯式傳入long型種子
  • 常用方法
Modifier and Type Method Description
public Xxx nextXxx() 獲取Xxx型僞隨機數

7.3 BigDecimal類

  • 更加精確表示、計算浮點數。
  • 構造器:
Modifier and Type Method Description
public BigDecimal(String val) 傳入字符串創建對象
public BigDecimal(BigInteger val) 傳入BigInteger對象
  • 常用方法
Modifier and Type Method Description
public static BigDecimal valueOf(double/long val) 返回BigDecimal對象
public BigDecimal add(BigDecimal augend) 加法
public BigDecimal subtract(BigDecimal subtrahend) 減法
public BigDecimal multiply(BigDecimal multiplicand) 乘法
public BigDecimal divide(BigDecimal divisor) 除法

注意

  1. 創建BigDecimal對象時,不要直接使用double浮點數作爲構造器參數,這樣會造成精度丟失問題。解決:通過valueOf()方法轉爲BigDecimal對象。
    double a = 3.14159265357;
    BigDecimal bigA = BigDecimal.valueOf(a);
    
  2. double浮點數進行加、減、乘、除基本運算,先包裝成BigDecimal對象,再調用相應方法。

8 日期、時間類

8.1 Date類

  • 毫秒值相關的Date類(日期精確到秒)屬於java.util
  • 毫秒值:以公元1970年1月1日午夜0:00:00爲時間原點。
    • 當前毫秒值:System.currentTimeMillis(),返回long類型.
  • Date類常用方法
Modifier and Type Method Description
public Date() 獲得當前操作系統的時間和日期
public Date(long date) 傳遞毫秒值,將毫秒值轉化爲對應日期(Date)對象
public long getTime() 返回日期對象對應的毫秒值。
public void setTime(long time) 將毫秒值設置成日期對象

8.2 Calendar類

  • Calendar類是一個抽象類,直接已知子類:GregorianCalendar類
  • Calendar類寫了靜態方法getInstance(),直接返回子類對象,所以不需要new,子類對象可通過靜態方法獲得。
    Calendar cal=Calendar.getInstance();
    System.out.println(cal);
    
  • Calendar常用方法
Modifier and Type Method Description
public static Calendar getInstance() 獲取子類實例
public final Date getTime() 抽取Date對象
public int get(int field) 返回指定日曆字段的值
public void set(int field, int value) 將給定的日曆字段設值
abstract public void add(int field, int amount) 對給定日曆字段添加/減少指定值

日期計算實例

  1. 計算自己年齡
    System.out.println("輸入出生日期(格式:yyyy-MM-dd): ");
    String birthDay=new Scanner(System.in).next();
    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
    Date dateBirth = simpleDateFormat.parse(birthDay);  //字符串轉Date
    long ms=System.currentTimeMillis()-dateBirth.getTime();  //毫秒值差值
    System.out.println("天數:"+ms/1000/60/60/24);
    System.out.println("年數:"+ms/1000/60/60/24/365);
    
  2. 閏年計算:日曆設置到指定年份3月1日,add向前偏移1天,獲取天數,29爲閏年。
    while(true) {
       System.out.println("輸入年份:");
       int year=new Scanner(System.in).nextInt();
       Calendar calendar=Calendar.getInstance();  //創建Calendar子類對象
       calendar.set(year, 2, 1);  //指定3月1號(國外是0-11月)
       calendar.add(Calendar.DAY_OF_MONTH, -1);  //向前偏移1天
       if(calendar.get(Calendar.DAY_OF_MONTH)==29) {
           System.out.println(year+" 是閏年!!");
       }else {
            System.out.println(year+" 不是閏年!!");				
       }
    }
    

9 格式化相關類

9.1 Format抽象類

  • Format是抽象類,已知直接子類有DateFormat類, MessageFormat類, NumberFormat類
  • Format類常用方法
Modifier and Type Method Description
public final String format (Object obj) 格式化對象生成字符串
public Object parseObject(String source) 字符串解析爲對象

9.2 NumberFormat格式化數字

  • NumberFormat也是一個抽象基類,通過getXxxInstance()靜態方法創建類對象。
  • NumberFormat類常用方法
Modifier and Type Method Description
public final static NumberFormat getIntegerInstance() 返回默認Locale的整數格式器
public static NumberFormat getInstance(Locale inLocale) 返回指定Locale的貨幣格式器
public final String format(double number) 將double數字格式化爲字符串
public Number parse(String source) 將字符串解析爲Number對象

9.3 DateFormat格式化日期、時間

  • DateFormat也是一個抽象類,通過getXxxInstance()方法獲取對象。
  • DateFormat類常用方法
Modifier and Type Method Description
public final static DateFormat getDateInstance(int style, Locale aLocale) 返回日期格式器
public final static DateFormat getTimeInstance(int style, Locale aLocale) 返回時間格式器
public final String format(Date date) Date對象格式化爲字符串
public Date parse(String source) 字符串解析爲Date對象

注意:DateFormat類的parse()方法只能解析特定格式字符串,可使用SimpleDateFormat類靈活格式化和解析日期、時間。

日期格式化 :自己定義日期的格式。(日期轉字符串)

  1. 創建SimpleDateFormat(java.text包)對象,構造方法中寫入自定義日期格式(要求符合其Pattern規則).
  2. SimpleDateFormat對象調用format方法對日期格式化。
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日,hh:mm:ss");
    String date=sdf.format(new Date());
    System.out.println(date);  //輸出如:2018年11月15日,10:14:38
    

字符串轉日期

  1. 創建SimpleDateFormat(java.text包)對象,構造方法中指定日期格式。
  2. SimpleDateFormat對象調用parse方法,返回日期Date。
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(sdf2.parse("2018-11-15"));  //輸出如:Thu Nov 15 00:00:00 CST 2018
    

10 函數式接口

  • 函數式接口(Functional Interface):只包含一個抽象方法的接口。
  • 函數式接口可以用Lambda表達式創建匿名對象和重寫接口唯一的抽象方法。
    Lambda表達式內容參考Java面向對象的2.2小節方法重寫部分。

10.1 Consumer接口

  • 抽象方法
Modifier and Type Method Description
void accept(T t) 對給定參數執行此操作
  • 接口使用
  1. Iterable接口的forEach(Consumer action)方法
  2. Iterator接口的forEachRemaining(Consumer<? super E> action)方法
  3. 自定義的需要Consumer接口參數的方法。

10.2 Predicate接口

  • Predicate(謂詞)抽象方法
Modifier and Type Method Description
boolean test(T t) 由參數計算謂詞(true or false)
  • 接口使用
  1. Collection接口的removeIf(Predicate<? super E> filter)方法。
  2. 自定義的需要Predicate接口參數的方法。
    注意:函數式接口使用示例見Java集合2小節的遍歷集合元素部分。

11 基本數據類型對象包裝類

基本數據類型 字節型 短整型 整型 長整型 字符型 布爾型 浮點型 浮點型
數據類型 byte short int long char boolean float double
包裝類 Byte Short Integer Long Character Boolean Float Double
  • 對象包裝類在java.lang包中。
  • 對象包裝類用於基本數據和字符串之間的轉換。
    以整型爲例:
    • 字符串\rightarrow基本數據類型
      使用方法public static int parseInt(String s);
      int a=Integer.parseInt("123");
      System.out.println(a/10);  //輸出結果爲12
      
    • 基本數據類型\rightarrow字符串
    1. 使用toString方法public static String toString(int i);
      int a=123;
      String b = Integer.toString(a);
      System.out.println(b+456); //輸出結果爲字符串123456
      
    2. 只需要基本數據+""(簡單方法)
      int a = 12;
      String b = a+"";  //基本類型即轉爲字符串類型
      

注意:數據在byte範圍內,JVM不會重新new對象。(見Integer源碼)

Integer a2=127;
Integer a1=127;
System.out.println(a2==a1);  //true
System.out.println(a2.equals(a1));  //true
	
Integer b2=127;
Integer b1=127;
System.out.println(b2==b1);  //false
System.out.println(b2.equals(b1));  //true
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章