常用API
方法重載: 方法名相同,方法接收的參數不同
static: 修飾的類,可以直接使用類名進行調用
方法名 | 說明 |
---|---|
public static abs(int a) | 返回參數的絕對值 |
public static double ceil(double a) | 返回大于或等于 |
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() | 返回值為random的正值,[0.0, 1.0) |
Math
public class MathDemo {public static void main(String[] args) {// 返回參數的絕對值System.out.println(Math.abs(88));System.out.println(Math.abs(-88));System.out.println("--------");// 返回大于或等于參數的最小double值(double類型)System.out.println(Math.ceil(12.34));System.out.println(Math.ceil(12.01));System.out.println("--------");// 返回小于或等于參數的最大double值(double類型)System.out.println(Math.floor(12.34));System.out.println(Math.floor(12.01));System.out.println("--------");// 返回最接近參數的int值 - 四舍五入System.out.println(Math.round(12.34F));System.out.println(Math.round(12.56F));System.out.println("--------");// 返回兩個int值中較大的int值System.out.println(Math.max(66, 88));System.out.println("--------");// 返回兩個int值中較小的int值System.out.println(Math.min(66, 88));System.out.println("--------");// 返回a的b次冪System.out.println(Math.pow(2.0, 3.0));System.out.println("--------");// 返回一個隨機的double正值 [0.0, 1.0)System.out.println(Math.random());System.out.println((int) (Math.random() * 100));}
}
System
public static void exit(int status)
: 終止當前運行的Java虛擬機。該參數作為狀態代碼,非零狀態碼表示異常終止public static long currentTimeMillis()
: 返回當前時間(以毫秒為單位, 與1970年1月1日UTC之間的毫秒差值).
System包含幾個有用的類字段和方法,它不能被實例化
public class SystemDemo {public static void main(String[] args) {System.out.println("開始");// public static void exit(int status): 終止當前運行的Java虛擬機,非零表示異常終止
// System.exit(0);System.out.println("結束");// public static long currentTimeMillis(): 返回當前時間(以毫秒為單位)System.out.println(System.currentTimeMillis());// 計算當前時間與 UTC標準時間間隔多少天System.out.println(System.currentTimeMillis() * 1.0 / 1000 / 60 / 60 / 24 / 365 + "年");long start = System.currentTimeMillis();// 計算for循環的時間for (int i = 0; i < 10000; i++) {System.out.println(i);}long end = System.currentTimeMillis();System.out.println("循環10000次,耗時" + (end - start) + "毫秒");}
}
Object
類Object是類層次結構的根。每個類都有Object作為超類。所有對象(包括數組)都實現了這個類的方法
構造方法: public Object()
回想面向對象中,為什么說子類的構造方法默認訪問的是父類的無參構造方法?
因為它們的頂級父類,只有無參構造方法
看方法源碼: 選中方法,按下 ctrl + b
toString方法
有學生類如下:
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;}
}
測試類: 創建一個學生類并輸入
public class StudentDemo{public static void main(String[] args){Student s = new Student();s.setName("Marron");s.setAge(18);System.out.println(s); // com.marron_01.Student@2d98a335}
}
以上結果為什么會是: com.marron_01.Student@2d98a335
呢?
選中println方法
,按下ctrl + b
,同理.一層一層的往底層找去.得到如下的函數
public void println(Object x){String s = String.valueOf(x);synchronized(this){this.print(s);this.newLine();}
}public static String valueOf(Object obj){return obj == null ? "null" : obj.toString();
}public String toString() {return this.getClass().getName() + "@" + Integer.toHexString(this.hashCod());
}
當執行System.out.println(s)
的時候,根據println的定義,此時 Object x
中的x值為s
之后執行 String s = String.valueOf(x)
, 將x傳入 public static String valueOf(Object obj)
此時的obj為x(非空),因此會返回一個obj.toString()
. 此時的obj,實際上就是s。而Student類并沒有toString
方法.
這就涉及到一個隱式繼承.即所有的類最終都會繼承Object.而Object類中含有toString方法
.故上述的Student類聲明,實際上等同于下面:
public class Student extends Object{}
可以通過以下方式驗證:
public class StudentDemo{public static void main(String[] args){Student s = new Student();System.out.println(s); // com.marron_01.Student@2d98a335System.out.println(s.toString()); // com.marron_01.Student@2d98a335}
}
【小結】:
public String toString()
: 返回對象的字符串表示形式。一般來說,toString方法返回一個"toString"代表這個對象的字符串。結果應該是一個簡明扼要的表達,容易讓人閱讀。建議所有子類重寫此方法。
重寫如下:
// Student.java
public class Student{// 其他方法略@Overridepublic String toString() {return "Student{" + "name=" + "name" + "\" +", age=" + age + "}";}
}
equals
需求: 還是上面的學生類,創建2個學生實例.讓兩個學生實例的內容相同.
public class ObjectDemo{public static void main(String[] args){Student s1 = new Student();s1.setName("Marron");s1.setAge(18);Student s2 = new Student();s2.setName("Marron");s2.setAge(18);}
}
判斷兩個學生實例的內容是否相同:
使用Object自帶的equals進行比較
public boolean equals(Object obj){return this == obj;
}
tips: 調用時: s1.equals(s2); 此時比較的是s1和s2的地址值. 故需要重寫equals方法
public class Student{private String name;private int age;@Overridepublic boolean equals(Object o){if(this == o) return true;if( o == null || getClass() != o.getClass()) return false;Student student =(Student) o;if(age != student.age) return false;return name != null? name.equals(student.name) : student.name == null;}
}
Arrays
冒泡排序
冒泡排序: 一種排序的方式,對要進行排序的數據中相鄰的數據進行兩兩比較,將較大的數據放在后面,依次對所有的數據進行操作,直至所有數據按要求完成排序.
- 如果有n個數據進行排序,總共需要比較n-1此
- 每一次比較完畢,下一次的比較就會少一個數據參與
public class ArrayDemo{public static void main(String[] args){int[] arr = {24, 69, 80, 57, 13};System.out.println("排序前: " + array2String(arr));// 排序int MAX_LEN = arr.length - 1;for(int x =0; x< MAX_LEN; x++){for(int i = 0; i< MAx_len - X; i++){if(arr[i] > arr[i+1]){int tmp = arr[i];arr[i] = arr[i+1];arr[i+1] = tmp;}}}System.out.println("排序后: " + array2String(arr));}public static String array2String(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("]");return sb.toString();}
}
使用Array包提供的方法進行排序
Arrays類包含用于操作數組的各種方法
方法名 | 說明 |
---|---|
public static String toString(int[] a) | 返回指定數組的內容的字符串表示形式 |
public static void sort(int[] a) | 按照數字順序排列指定的數組 |
工具類的設計思想:
- 構造方法用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 |
public class IntegerDemo{public static void main(String[] args){Integer i1 = Integer.valueOf(100);Integer i2 = Integer.valueOf("100");System.out.println(i1);System.out.println(i2);}
}
int和String的互相轉換
基本類型包裝類的最常見操作就是: 用于基本類型和字符串之間的相互轉換
- int轉換為String
public static String valueOf(int i)
: 返回int參數的字符串表示形式。該方法時String類中的方法
public class IntegerDemo{public static void main(String[] args){int num = 100;String s2 = String.valueOf(num);}
}
- String類型轉換為int
public static int parseInt(String s)
: 將字符串解析為int類型。該方法是Integer類中的方法
public class IntegerDemo{public static void main(String[] args){String s = "100";int x = Integer.parseInt(s);}
}
栗子 - 字符串中數據排序
需求: 有一個字符串: “91 27 46 38 50”,請寫程序實現最終輸出結果是: “27 38 46 50 91”
思路是:
- 首先使用String[]接收split方法按空格劃分的字符數組
- 將String[]類型轉換成int[]類
- 使用Arrays.sort方法對int[] 進行排序
- 使用StringBuilder將int[]轉換成StringBuilder類
- 將StringBuilder類轉換成字符串得到最終結果
import java.util.Arrays;
public class IntegerTest{public static void main(String[] args){String s = "91 27 46 38 50";String[] strArr = s.split(" ");int[] arr = new int[strArr.length];for(int i = 0 ; i< arr.length; i++){arr[i] = Integer.parseInt(strArr[i]);}Arrays.sort(arr);StringBuilder sb = new StringBuilder();for(int i =0; i< arr.length; i++){if(i == arr.length -1){sb.append(arr[i]);} else {sb.append(arr[i]).append(" ");}}String res = sb.toString();System.out.println(res);}
}
自動裝箱和拆箱
- 裝箱: 把基本數據類型轉換為對應的包裝類類型
- 拆箱: 把包裝類類型轉換為對應的基本數據類型
// 自動裝箱
Integer i = 100; // JDK底層自動調用,等價于: Integer i = Integer.valueOf(100);// 自動拆箱
i += 200; // JDK底層自動調用,等價于: i = i.intValue() + 200. 然后自動裝箱
注意: 在使用包裝類類型的時候,如果做操作,最后先判斷是否為null
日期類
Date類
方法名 | 說明 |
---|---|
public Date() | 分配一個Date對象,并初始化,以便它代表它被分配的時間,精確到毫米 |
public Date(long date) | 分配一個Date對象,并將其初始化為表示標準基準時間起指定的毫秒數 |
public class DateDemo01{public static void main(String[] args){Date d1 = new Date();}
}
Date類的常用方法
方法名 | 說明 |
---|---|
public long getTime() | 獲取的是日期對象從1970年1月1日00:00:00到現在的毫秒值 |
public void setTime(long time) | 設置時間,給的是毫秒值 |
public class DateDemo02{public static void main(String[] args){// 創建日期對象Date d = new Date();// public long getTime();System.out.println(d.getTime() * 1.0 / 1000/60/60/24/365 + "年");long time = System.currentTimeMillis();d.setTime(time);System.out.println(d);}
}
SimpleDateFormat類概述
SimpleDateFormat是一個具體的類,用于以區域設置敏感的方式格式化和解析日期。我們重點學習日期格式化和解析
日期和時間格式由日期和時間模式字符串指定,在日期和時間模式字符串中,從’A’到’Z’以及從’a’到’z’引號的字母被解釋為表示日期或時間字符串的組件的模式字母
字母 | 含義 |
---|---|
y | 年 |
M | 月 |
d | 日 |
H | 時 |
m | 分 |
s | 秒 |
- 格式化(從Date到String):
public final String format(Date date)
: 將日期格式化成日期/時間字符串
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo{public static void main(String[] args){Date d = new Date(); // 生成一個距離UTC的毫秒時間// 創建一個時間規范: 該規范的format方法,會將Date格式轉換成想要的日期String格式SimpleDateFormate sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");String s = sdf.format(d);System.out.println(s); // 2020年04月03日 23:42:04}
}
- 解析(從String到Date):
public Date parse(String source)
: 從給定字符串的開始解析文本以生成日期
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo{public static void main(String[] args) throws ParseException{String s = "2048-08-08 11:11:11";SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date d = sdf.parse(s);System.our.println(d); // Wed Aug 08 11:11:11 CST 2040}
}
栗子 - 日期工具類
需求: 定義一個日期工具類(DateUtils), 包含兩個方法: 把日期轉換為指定格式的字符串;把字符串解析為指定格式的日期,然后定義一個測試類(DateDemo),測試日期工具類的方法
- 包裝構造方法私有
public class DateUtils{private DateUtils(){}
}
以上包裝了該類無法被實例化,只能通過類.方法名的格式調用暴露出來的公共接口,下面是整體實現:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;public class DateUtils{private DateUtils(){}// 把日期轉換成字符串public static String dateToString(Date d, String format){SimpleDateFormat sdf = new SimpleDateFormat(format);return new String(sdf.format(d));}// 把字符串轉換成日期public static Date stringToDate(String s, String format) throws ParseException{SimpleDateFormat sdf = new SimpleDateFormat(format);return sdf.parse(s);}
}
// 測試類如下
import java.text.ParseException;
import java.util.Date;public class DateDemo {public static void main(String[] args) throws ParseException {// 創建日期對象Date d = new Date();String s1 = DateUtils.dateToString(d, "yyyy年MM月dd日");System.out.println(s1);String s2 = "2020-08-08 11:11:11";Date dd = DateUtils.stringToDate(s2, "yyyy-MM-dd HH:mm:ss");System.out.println(dd);}
}
Calendar類
Calendar為某一時刻和一組日歷字段之間的轉換提供了一些方法,并為操作日歷字段提供了一些方法
Calendar提供了一個類方法getInstance用于獲取Calendar對象,其日歷字段已使用當前日期和時間初始化:Calendar rightNow = Calendar.getInstance()
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) + 1;int date = c.get(Calendar.DATE);System.out.println(year + "年" + month + "月" + date + "日");}
}
Calendar的常用方法
方法名 | 說明 |
---|---|
public int get(int field) | 返回給定日歷字段的值 |
public abstract void add(int field, int amount) | 根據日歷的規則,將指定的時間量添加或減去給定的日歷字段 |
public final void set(int year, int month, int date) | 設置當前日歷的年月日 |
import java.util.Calendar;public class CalendarDemo{public static void main(String[] args){Calendar c = Calendar.getInstance();// 10年后的7天前c.add(Calendar.YEAR,10);c.add(Calendar.DATE, -7);int year = c.get(Calendar.YEAR);int month= c.get(Calendar.MONTH) + 1;int date = c.get(Calendar.DATE);System.out.println(year + "年" + month + "月" + date + "日");// 設置時間為2048年11月11日c.set(2048,10,11);}
}
二月天
需求: 獲取任意一年的二月有多少天
【思路】: 首先獲取鍵盤輸入的年份,然后設置當前日期為該年的3月1日,之后設置天數建議,最好使用c.get獲取天數.
import java.util.Calendar;
import java.util.Scanner;public class CalendarTest{public static void main(String[] args){Scanner sc = new Scanner(System.in);System.out.println("請輸入年份");int year = sc.nextInt();Calendar c = Calendar.getInstance();c.set(year, 2, 1);c.add(Calendar.DATE, -1);int day = c.get(Calendar.DATE);System.out.println(year + "年的二月份有" + day + "天");}
}