JAVA打怪之路 - Java常用類 -日期和時間、Java比較器、數學公式

Java常用類 - 日期和時間、Java比較器、數學公式

一、日期時間API

在這裏插入圖片描述
① java.lang.System類 JDK8之前
在這裏插入圖片描述
② java.util.Date類 JDK8之前
在這裏插入圖片描述
③ java.text.SimpleDateFormat類 ( 格式化和解析日期的具體類 )

在這裏插入圖片描述

Date date = new Date(); // 產生一個Date實例
// 產生一個formater格式化的實例
SimpleDateFormat formater = new SimpleDateFormat();
System.out.println(formater.format(date));// 打印輸出默認的格式
SimpleDateFormat formater2 = new SimpleDateFormat("yyyy年MM月dd日 EEE HH:mm:ss");
System.out.println(formater2.format(date));
try {
    // 實例化一個指定的格式對象
    Date date2 = formater2.parse("2008年08月08日 星期一 08:08:08");
    // 將指定的日期解析後格式化按指定的格式輸出
    System.out.println(date2.toString());
} catch (ParseException e) {
    e.printStackTrace();
}

④ java.util.Calendar(日曆)類 JDK8之前
在這裏插入圖片描述
⑤ JDK8新日期時間API

JDK8以前日期時間API的侷限性:
在這裏插入圖片描述
5.1 LocalDate、LocalTime、LocalDateTime

說明:LocalDate、LocalTime、LocalDateTime 類是其中較重要的幾個類,它們的實例是不可變的對象,分別表示使用 ISO-8601日曆系統的日期、時間、日期和時間。它們提供了簡單的本地日期或時間,並不包含當前的時間信息,也不包含與時區相關的信息。

在這裏插入圖片描述

5.2 Instant (瞬時)
在這裏插入圖片描述

5.3 java.time.format.DateTimeFormatter 類
在這裏插入圖片描述
5.4 其他類
在這裏插入圖片描述
5.5 與傳統日期處理的轉換
在這裏插入圖片描述

二、Java比較器

① 自然排序:java.lang.Comparable
在這裏插入圖片描述
在這裏插入圖片描述

class Goods implements Comparable {
    private String name;
    private double price;
    //按照價格,比較商品的大小
    @Override
    public int compareTo(Object o) {
        if(o instanceof Goods) {
            Goods other = (Goods) o;
            if (this.price > other.price) {
                return 1;
            } else if (this.price < other.price) {
                return -1;
            }
            return 0;
        }
        throw new RuntimeException("輸入的數據類型不一致");
    }
    //構造器、getter、setter、toString()方法略
}
public class ComparableTest{
    public static void main(String[] args) {
        Goods[] all = new Goods[4];
        all[0] = new Goods("《紅樓夢》", 100);
        all[1] = new Goods("《西遊記》", 80);
        all[2] = new Goods("《三國演義》", 140);
        all[3] = new Goods("《水滸傳》", 120);
        Arrays.sort(all);
        System.out.println(Arrays.toString(all));
    }
}

② 定製排序:java.util.Compartor
在這裏插入圖片描述

Goods[] all = new Goods[4];
all[0] = new Goods("War and Peace", 100);
all[1] = new Goods("Childhood", 80);
all[2] = new Goods("Scarlet and Black", 140);
all[3] = new Goods("Notre Dame de Paris", 120);
Arrays.sort(all, new Comparator() {
    @Override
    public int compare(Object o1, Object o2) {
        Goods g1 = (Goods) o1;
        Goods g2 = (Goods) o2;
        return g1.getName().compareTo(g2.getName());
    }
});
System.out.println(Arrays.toString(all));

三、System 類
在這裏插入圖片描述
在這裏插入圖片描述

四、Math 類
在這裏插入圖片描述

六、BigInteger與BigDecimal 類

BigInteger

在這裏插入圖片描述
在這裏插入圖片描述

BigDecimal 類
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章