Java基礎(4):Java常見API
阿新 • • 發佈:2018-12-25
文章目錄
1 API
- Application Program I
- 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) | 設定特定輸入分隔符 |
注意:
- Xxx不存在時表示字串String。
- 預設情況下,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) | 替換 |
注意:
- matches方法要從頭到尾全匹配才返回true,原因是其方法本質是
matches("^yourregex$")
- Java字串中反斜槓(\)本身需要轉義,因此兩個反斜槓(\\)實際上相當於一個,如轉義字元
\d
在Java中需要表示為\\d
. - 正則表示式內容參考這裡。
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物件是正則表示式編譯後在記憶體中的表現形式。
- 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) | 除法 |
注意:
- 建立BigDecimal物件時,不要直接使用double浮點數作為構造器引數,這樣會造成精度丟失問題。解決:通過valueOf()方法轉為BigDecimal物件。
double a = 3.14159265357; BigDecimal bigA = BigDecimal.valueOf(a);
- 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) | 對給定日曆欄位新增/減少指定值 |
日期計算例項:
- 計算自己年齡
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);
- 閏年計算:日曆設定到指定年份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類
靈活格式化和解析日期、時間。
日期格式化 :自己定義日期的格式。(日期轉字串)
- 建立SimpleDateFormat(
java.text
包)物件,構造方法中寫入自定義日期格式(要求符合其Pattern規則). - 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
字串轉日期:
- 建立SimpleDateFormat(
java.text
包)物件,構造方法中指定日期格式。 - 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) | 對給定引數執行此操作 |
- 介面使用
- Iterable介面的
forEach(Consumer action)
方法 - Iterator介面的
forEachRemaining(Consumer<? super E> action)
方法 - 自定義的需要Consumer介面引數的方法。
10.2 Predicate介面
- Predicate(謂詞)抽象方法
Modifier and Type | Method | Description |
---|---|---|
boolean | test(T t) | 由引數計算謂詞(true or false) |
- 介面使用
- Collection介面的
removeIf(Predicate<? super E> filter)
方法。 - 自定義的需要Predicate介面引數的方法。
注意:函式式介面使用示例見Java集合2小節的遍歷集合元素部分。
11 基本資料型別物件包裝類
基本資料型別 | 位元組型 | 短整型 | 整型 | 長整型 | 字元型 | 布林型 | 浮點型 | 浮點型 |
---|---|---|---|---|---|---|---|---|
資料型別 | byte | short | int | long | char | boolean | float | double |
包裝類 | Byte | Short | Integer | Long | Character | Boolean | Float | Double |
- 物件包裝類在
java.lang
包中。 - 物件包裝類用於基本資料和字串之間的轉換。
以整型為例:- 字串
基本資料型別
使用方法public static int parseInt(String s);
int a=Integer.parseInt("123"); System.out.println(a/10); //輸出結果為12
- 基本資料型別 字串
- 使用toString方法
public static String toString(int i);
int a=123; String b = Integer.toString(a); System.out.println(b+456); //輸出結果為字串123456
- 只需要
基本資料+""
(簡單方法)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