JavaAPI-工具類

煙雨鋒城ゝ發表於2020-12-03

java提供了一系列的工具類,我們應用的時候可以訪問它們的屬性和方法,但是工具類很多,記住常用的即可!使用的時候就去API幫助文件手冊查詢,有離線的和線上版本的,離線的百度搜尋一下都能找到

線上官網:https://docs.oracle.com/javase/8/docs/api/

中文參考官網:https://www.matools.com/api/java8

Object

之前我們說過Object是所有類的根類,那麼說具體的工具類之前,我們先說一下Object

說白了Object也是一個類,那麼肯定也有對應的方法


Object所有方法的作用在API幫助文件手冊都能找到,這裡就介紹幾個方法,測試之前先寫一段程式碼

public class MobilePhone {
    private String brand;
    private int price;

    public MobilePhone() {
    }

    public MobilePhone(String brand, int price) {
        this.brand = brand;
        this.price = price;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }
}
public class TestMobilePhone {
    public static void main(String[] args) {
        MobilePhone phone=new MobilePhone();
        //子類沒對Object重寫,都呼叫的是Object類的方法
        
        //getClass():獲取類的全限定名(包名+類名),執行結果:class com.ty.Packaging.MobilePhone
        System.out.println(phone.getClass());
        
        //hashCode():獲取雜湊碼,執行結果:703360008,注意:每次執行hashCode都可能不同
        //雜湊碼:將物件在堆中的地址,進行雜湊演算法,會返回一個碼稱為雜湊碼
        System.out.println(phone.hashCode());
        
        //獲取該物件字串的表示資訊:執行結果:com.ty.Packaging.MobilePhone@519dcf69
        //預設此字串的含義:getClass().getName() + "@" + Integer.toHexString(hashCode());
        // Integer.toHexString()的意思是將一個數用十六進位制展示
        System.out.println(phone.toString());
        
        MobilePhone phone1=new MobilePhone("P40",4488);
        MobilePhone phone2=new MobilePhone("P40",4488);
        //比較phone1物件和phone2物件內容是否相等,此處現在執行結果是false,因為預設呼叫的Object裡的equals方法還是用==判斷,比較的是兩個物件的地址是否相等,return (this == obj);
        System.out.println(phone1.equals(phone2));
    }
}
//要想顯示物件資訊的時候好看一些,判斷2個物件內容是否相等而不是比較地址的話,MobilePhone就可以重寫toString和equals方法
//自己進行重寫equals 
@Override
    public boolean equals(Object obj) {
        MobilePhone phone = (MobilePhone) obj;
        if (this.getBrand() == phone.getBrand() && this.getPrice() == phone.getPrice()) {
            return true;
        }
        return false;
    }
//IDE幫助我們重寫equals
 @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MobilePhone phone = (MobilePhone) o;
        return price == phone.price &&
                Objects.equals(brand, phone.brand);
    }

//自己進行重寫toString
 @Override
    public String toString() {
        return "手機品牌是:"+this.getBrand()+"手機價格是:"+this.getPrice();
    }
//IDE幫助我們重寫toString
 @Override
    public String toString() {
        return "MobilePhone{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }

//這樣 System.out.println(phone1.equals(phone2));輸出的就是:true
//System.out.println(phone1.toString());輸出的就是:MobilePhone{brand='P40', price=4488}

包裝類

之前我們都是用基本都是基本型別儲存資料的,基本型別的好處就是不需要new建立,也就不會在堆中開闢空間,直接在棧中儲存會更加高效。但是我們瞭解java最主要的就是物件導向的特性,即能操作物件的屬性和方法,基本型別就不能滿足要求了,然後java就引進了包裝類

基本資料型別包裝類父類
byteByteNumber------->Object
booleanBooleanObject
shortShortNumber------->Object
charCharacterObject
intIntegerNumber------->Object
longLongNumber------->Object
floatFloatNumber------->Object
doubleDoubleNumber------->Object

Integer

用Integer做案例來進行講解,此類掌握了之後其它的包裝類大同小異

從上面API幫助文件手冊可以看出幾個資訊,所有的類都可以從 API幫助文件手冊上檢視!

  1. 所屬包:Integer類所屬java.lang下,使用的時候無需導包

  2. 繼承資訊:Integer類繼承自Number類,再往上繼承自Object類

  3. 實現資訊:Integer類實現Serializable和Comparable<Integer>介面

  4. 類的附加資訊:Integer類被final關鍵字修飾,不能有子類繼承

  5. 類的描述資訊:是對基本資料型別的封裝,Integer是對int的封裝。而且此類提供了處理int的時候的屬性和方法

  6. 類的開始生效版本:JDK1.0

  7. 再接著往下看API你能看到具體的操作方法,也能看到具體操作的描述資訊,這裡就不截出來了

演示一下操作方法,詳細的還是看API比較好

//操作屬性
System.out.println(Integer.MAX_VALUE); //返回最大值
System.out.println(Integer.MIN_VALUE); //返回最小值
//構造方法
Integer integer1 = new Integer(10);
Integer integer2 = new Integer("123");
System.out.printf("integer1:%d , integer2:%d", integer1, integer2);

簡單看一下原始碼的處理流程:

//傳進的int資料傳進底層要封裝進的value裡
private final int value;
public Integer(int value) {
        this.value = value;
}

//傳進的String資料呼叫parseInt,將String轉換成int型別資料,然後傳進底層要封裝進的value裡,如果轉換不成功就報NumberFormatException異常
public Integer(String s) throws NumberFormatException {
        this.value = parseInt(s, 10);
}

另外包裝型別和基本資料型別是互相能進行轉換的,基本資料型別轉換為包裝型別稱為裝箱,反之成為拆箱

在jdk5之後增加了一種機制,提供了自動裝箱和自動拆箱這種特性,能很好更好的完成轉換功能

Integer integer = 18; //自動裝箱,基本型別-》包裝型別
System.out.println(integer);
int num = integer1;
System.out.println(num); //自動拆箱,包裝型別-》基本型別

看一下反編譯之後的程式碼

可見底層實現自動裝箱就是呼叫了valueOf()方法,自動拆箱就是呼叫了intValue()方法

看一下ValueOf()方法的實現

private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            int h = 127;        
            high = h; //high = 127

            cache = new Integer[(high - low) + 1]; //cache = new Integer[(127 - (-128)) + 1]
            								 	  // 也就是cache[] = new Integer[256]
            int j = low; 					      // int j = -128
            for(int k = 0; k < cache.length; k++) 
                cache[k] = new Integer(j++); //cache[256]={-128,-127,-126,......,126,127}

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high) //if(i >= -128 && i <= 127)
            return IntegerCache.cache[i + (-IntegerCache.low)]; //return IntegerCache.cache[i + (-128)]
        return new Integer(i); //不符合範圍就new一個
    }
            
 //總結:如果值是-128到127之間就從IntegerCache.cache陣列中獲取,如果不在這個範圍,就new
//這段程式碼就是呼叫了上面那段valueOf的程式碼,判斷實現
Integer integer3 = 12;
Integer integer4 = 12;
Integer integer5 = 128;
Integer integer6 = 128;
System.out.println(integer3 == integer4); // true,比較的是數值
System.out.println(integer5 == integer6); // false,比較的是地址

再演示一個方法:

Integer integer7=10;
Integer integer8=12;
System.out.println(integer.compareTo(integer8));// 執行結果:-1

/*
原始碼:
public int compareTo(Integer anotherInteger) {
        return compare(this.value, anotherInteger.value);
}
public static int compare(int x, int y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }
*/

Character

可以從API幫助文件手冊檢視具體資訊,檢視方法參考上面的Integer,這裡演示幾個常用的方法!

public class TestCharacter {
    public static void main(String[] args) {
        Character ch=new Character('a');
        System.out.println(Character.isDigit(ch)); //判斷是否為數字
        System.out.println(Character.isLetter(ch)); //判斷是否為字母
        System.out.println(Character.isUpperCase(ch)); //判斷是否為大寫
        System.out.println(Character.isLetter(ch)); //判斷是否為小寫
        System.out.println(Character.isWhitespace(ch)); //判斷是否為空格

        System.out.println(Character.toUpperCase(ch)); //轉換為大寫
        System.out.println(Character.toLowerCase('A')); //轉換為小寫
    }
}

字串類

String

除了從API手冊上檢視此類的資訊,還可以從原始碼上檢視

package java.lang;

/**
 * The <code>String</code> class represents character strings. All
 * string literals in Java programs, such as <code>"abc"</code>, are
 * implemented as instances of this class.
 * 類的上面有許多註釋,這些註釋都不是白來的,API的描述資訊也是從這些註釋得來的
 * @since   JDK1.0
 */
public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

通過看原始碼,可得以下基本資訊:

  1. 所屬包:String類所屬java.lang下,使用的時候無需導包

  2. 繼承資訊:String類繼承自Object類

  3. 實現資訊:String類實現Serializable,Comparable<Integer>和CharSequence介面

  4. 類的附加資訊:String類被final關鍵字修飾,不能有子類繼承;"abc"是String類下的一個具體的物件

  5. 類的描述資訊:String是對字元陣列封裝,String的內容存放在char value[]中,而且此陣列被final修飾,即字串不可被修改

  6. 類的開始生效版本:JDK1.0

  7. 再接著往下看原始碼你能看到具體的操作方法,而且也能看見對應操作的描述資訊

下面演示一下具體操作,詳細的你最好還是看API或者原始碼

//建立字串
public class TestString {
    public static void main(String[] args) {
        /**這種方式先在常量池中檢視是否具有"abc"的儲存空間
         * 如果有的話直接指向,如果沒有就先建立再指向
         * str1指向的是常量池的空間地址
         */
        String str1 = "abc";

        /**new這種方式,會先在堆中開闢一個空間,裡面有個value屬性,指向常量池的空間
         * 如果常量池中有"abc"的話 value直接指向,如果沒有就先建立然後 value再指向
         * new指向的是堆中的空間地址
         */
        String str2 = new String("abc");
        String str3 = new String(new char[]{'a', 'b', 'c'});
        String str4 = "hello";
        String str5 = str4 + "java";
    }
}

此外還有一種方式

String str4 = "hello";
String str5 = str4 + "java";

/*這種方式其實是建立了StringBuilder字串類,通過反彙編的方式,可能有利於理解,反彙編的命令:javap -c class檔案
  	  39: ldc           #6              // String hello	
  	  				      String str4 = "hello";
      41: astore        4
      43: new           #7                  // class java/lang/StringBuilder
      					      new StringBuilder
      46: dup
      47: invokespecial #8                  // Method java/lang/StringBuilder."<init>":()V
      					      StringBuilder sb=new StringBuilder();
      50: aload         4
      52: invokevirtual #9                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;   
                                               sb.append(str4);
      55: ldc           #10                 // String java
      					       String str = "java";
      57: invokevirtual #9                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;   
                                               sb.append(str);
      60: invokevirtual #11                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
						將StringBuilder型別轉換成String型別
//常用方法
System.out.println(str1.length()); //獲取字串的長度

System.out.println(str1.isEmpty()); //判斷字串是否為空

System.out.println(str1.charAt(1)); //獲取字串指定索引的單個字元,索引從0開始

System.out.println(str1.indexOf("b")); //獲取字元在字串中第一次出現的索引,如果找不到,返回-1

System.out.println(str1.lastIndexOf("b")); //獲取字元在字串中最後一次出現的索引,如果找不到,返回-1

System.out.println(str1.substring(1)); //擷取指定範圍的子串

System.out.println(str1.equals("abcd")); //判斷兩個字串內容是否相等,Object類之下的系統子類基本都重寫了equals方法

System.out.println(str1.equalsIgnoreCase("ABCD")); //忽略大小寫,判斷內容是否相等

System.out.println(str1.compareTo("abcd")); //按照Unicode的順序比較兩個字串,如果前者大,則返回正數,後者大,則返回負數,如果相等,返回0

System.out.println(str1.toUpperCase()); //轉換成大寫

System.out.println("ABCD".toLowerCase()); //轉換成小寫

System.out.println(str1.concat("def")); //拼接字串

System.out.println("智障,CNM".replace("CNM", "xxx")); //替換字串中的字元

String poem = "E:\\附加專案\\附加-project";
String[] split = poem.split("\\\\"); //以指定字元分割字串

for (int i = 0; i < split.length; i++) {
    System.out.println(split[i]);
}

str="              abc          ";
System.out.println(str);
System.out.println(str.trim()); //去除前後空格

String str = "hello";
char[] array = str.toCharArray(); //轉換成字元陣列
for (int i = 0; i < array.length; i++) {
    System.out.println(array[i]);
}

String name = "john";
int age = 10;
double score = 98.3 / 3;
char gender = '男';
//format():格式字串,佔位符:%s 字串 %c 字元 %d 整型 %.f 浮點型,.f之前可以加數字表示保留幾位小數
String info = String.format("我的名字%s,年齡:%d,考試成績:%f,性別:%c", name, age, score, gender);
System.out.println(info);

瞭解一下equals和compareTo的原始碼

/*	String str1 = "abcd";
	String str2 = "abcd"
	System.out.println(str1.equals(str2)); 
*/
private final char value[];

public boolean equals(Object anObject) {
        if (this == anObject) {		//if (str1 == str2),比較兩個物件的地址,相同就直接返回true
            return true;
        }
        if (anObject instanceof String) {	//判斷傳入的str2是不是String的例項,不是的話直接返回false
            String anotherString = (String)anObject;  // Object型別的str2向下轉型為String型別
            int n = value.length;					  // n = str1.length
            if (n == anotherString.value.length) {	  // if (n == str.length),判斷長度不等的話就返回false
                char v1[] = value;					  // v1[] = str1{'a','b','c','d'}
                char v2[] = anotherString.value;   	  // v2[] = str2{'a','b','c','d'}
                int i = 0;
                while (n-- != 0) {					//對陣列進行遍歷
                    if (v1[i] != v2[i])				//一位一位取出來進行遍歷,對應位不等的話的話就返回false
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }
/*	String str1 = "abcd";
	String str2 = "abcd"
	System.out.println(str1.equals(str2)); 
*/
private final char value[];

public int compareTo(String anotherString) {
        int len1 = value.length;			 // len1 = str1的長度:4
        int len2 = anotherString.value.length; // len2 = str2的長度:4
        int lim = Math.min(len1, len2);		   // 取小的那個值,即:lim = 4
        char v1[] = value;					   // v1[] = str1{'a','b','c','d'}
        char v2[] = anotherString.value;	   // v2[] = str2{'a','b','c','d'}

        int k = 0;  
        while (k < lim) {
            char c1 = v1[k]; //c1 = v1[0],c1 = v1[1],c1 = v1[2],c1 = v1[3]
            char c2 = v2[k];// c2 = v2[0],c2 = v2[1],c2 = v2[2],c2 = v2[3]
            if (c1 != c2) { // 分別對應判斷是否相等,如果相等直接k++,如果不等先返回兩個數的差值,然後進行k++
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2; //如果經過上面那個步驟判斷每位數都相同,兩個數長度不同的話就返回它倆的長度差
    }

String這種方式建立字串,因為它是不可變的每次增加的時候實際上是重新開闢空間儲存

//衡量一些程式碼走完所需的時間
long start = System.currentTimeMillis();

for (int i = 0; i < 10000; i++) {
    str += "hello";
}
long end = System.currentTimeMillis();
System.out.println("耗時:" + (end - start));

針對這種效率問題,java提供了另外一種表示字串的類StringBuilder 和 StringBuffer

StringBuffer

還是簡單看一下原始碼

/**
 * A thread-safe, mutable sequence of characters.
 * A string buffer is like a {@link String}, but can be modified. At any
 * point in time it contains some particular sequence of characters, but
 * the length and content of the sequence can be changed through certain
 * method calls.
 * @since   JDK1.0
 *
 * 執行緒安全[多執行緒]的可變字元序列,字串緩衝區類似於String,可以被修改,可以通過某些方法呼叫來更改序列的長度和內容。JDK1.0就有
 */
public final class StringBuffer
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
{
//繼承自AbstractStringBuilder類

/**
 * A mutable sequence of characters.
 * <p>
 * Implements a modifiable string. At any point in time it contains some
 * particular sequence of characters, but the length and content of the
 * sequence can be changed through certain method calls.
 *
 * 可變的字元序列,實現可修改的字串。它在任何時間點都包含某些特殊的字元序列,但是可以通過某些方法呼叫來更改序列的長度和內容。
 * @author      Michael McCloskey
 * @author      Martin Buchholz
 * @author      Ulf Zibis
 * @since       1.5
 */
abstract class AbstractStringBuilder implements Appendable, CharSequence {
    /**
     * The value is used for character storage.
     */
    char[] value; //存放的是可變的字元陣列

    /**
     * The count is the number of characters used.
     */
    int count; //value陣列中被使用的長度

//測試效率
public class TestStringBuffer {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        long start = System.currentTimeMillis();

        for (int i = 0; i < 10000; i++) {
            sb.append("hello"); //表示追加內容
        }
        long end = System.currentTimeMillis();
        System.out.println("耗時:" + (end - start));
    }
}

//同樣一段程式碼StringBuffer比String的效率高
//常用方法
StringBuffer sb = new StringBuffer("好好學習");
System.out.println(sb); //執行結果:好好學習;呼叫的是toString()方法,return new String(value, 0, count)

//增加
sb.append(",");
sb.append("天天向上");
System.out.println(sb); //執行結果:好好學習,天天向上

//刪除
sb.delete(4,sb.length());
System.out.println(sb); //執行結果:好好學習

//修改
sb.replace(2,sb.length(),"工作"); //替換
System.out.println(sb); //執行結果:好好工作

sb.insert(0,"dream!"); //插入
System.out.println(sb); //執行結果:dream!好好工作

//查詢
sb=new StringBuffer("abcdef");
System.out.println(sb.charAt(3));

StringBuilder

/**
 * A mutable sequence of characters.  This class provides an API compatible
 * with <code>StringBuffer</code>, but with no guarantee of synchronization.
 * This class is designed for use as a drop-in replacement for
 * <code>StringBuffer</code> in places where the string buffer was being
 * used by a single thread (as is generally the case).   Where possible,
 * it is recommended that this class be used in preference to
 * <code>StringBuffer</code> as it will be faster under most implementations.
 * @since       1.5
 *
 * 可變的字元序列,此類提供一個與 StringBuffer 相容的 API,但不保證同步(多執行緒問題)。該類被設計用作 StringBuffer 的一個簡易
 * 替換,用在字串緩衝區被單個執行緒使用的時候。如果可能,建議優先採用該類,因為在大多數實現中,它比StringBuffer要快,JDK1.5有
 */
public final class StringBuilder
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
{

StringBuilder 和 StringBuffer方法是一樣的,所以使用和StringBuffer一樣,這裡就不演示了

總結:String、StringBuffer 和StringBuilder的比較

  • String:不可變字元序列

  • StringBuilder 和 StringBuffer 非常類似,均代表可變的字元序列,而且方法也一樣

    • StringBuffer:可變字元序列、效率較高(增刪)、執行緒安全

    • StringBuilder(JDK1.5):可變字元序列、效率最高、執行緒不安全

應用場景:

  • 字串很少修改,被多個物件引用,使用String, 比如配置資訊等

  • 字串存在大量的修改操作,一般使用 StringBuffer 或 StringBuilder

    • 單執行緒:使用 StringBuilder

    • 多執行緒:使用StringBuffer

數學類

Math

/**
 * The class {@code Math} contains methods for performing basic
 * numeric operations such as the elementary exponential, logarithm,
 * square root, and trigonometric functions.
 *
 * Math類包含用於執行基本數值運算的方法,例如基本指數,對數,*平方根和三角函式。
 */
public final class Math {
    /**
     * Don't let anyone instantiate this class.
     */
    private Math() {} //構造器私有化代表不能建立Math物件
    
    //往下看屬性和方法能看出來都是被static關鍵字修飾,所以使用Math.來呼叫
//靜態導包
import static java.lang.Math.*;

public class TestMath {
    public static void main(String[] args) { //常用屬性:
        System.out.println(PI);
        //常用方法:
        System.out.println("隨機數:" + random());//[0.0 ~ 1.0)
        System.out.println("絕對值:" + abs(-80));
        System.out.println("向上取值:" + ceil(9.1));
        System.out.println("向下取值:" + floor(9.9));
        System.out.println("四捨五入:" + round(3.5));
        System.out.println("取大的那個值:" + max(3, 6));
        System.out.println("取小的那個值:" + min(3, 6));
        System.out.println("求冪:" + pow(2, 3));
        System.out.println("求開方:" + sqrt(9));
    }
}

Arrays類

/**
 * This class contains various methods for manipulating arrays (such as
 * sorting and searching). This class also contains a static factory
 * that allows arrays to be viewed as lists.
 *
 *此類包含各種用於處理陣列的方法(例如排序和搜尋)。此類還包含一個靜態工廠,該工廠可以將陣列視為列表。
 */
public class Arrays {
    // Suppresses default constructor, ensuring non-instantiability.
    private Arrays() {}
//常用方法
Integer[] arr = {10, 25, 32, 65, 47, 125, 845, 52};
System.out.println(Arrays.toString(arr)); //對陣列進行遍歷

Arrays.sort(arr);//排序,預設升序
System.out.println(Arrays.toString(arr));

Arrays.sort(arr, new Comparator() { //自定義排序
    @Override
    public int compare(Object o1, Object o2) {
        Integer n1 = (Integer) o1;
        Integer n2 = (Integer) o2;
        if (n1 > n2) {
            return -1;
        } else if (n1 < n2) {
            return 1;
        }
        return 0;
    }
});
System.out.println(Arrays.toString(arr));

Integer[] array = {85, 45, 25, 36, 521, 100};
Arrays.sort(array);
System.out.println(Arrays.toString(array));
// 二分法查詢:找出指定陣列中的指定元素對應的索引,必須是一個有序陣列
// 如果找到,就是對應的下標
// 如果沒有,就返回 -(low+1) low:應該存在的下標
System.out.println(Arrays.binarySearch(array, 455));

String[] strArr = new String[]{"a", "bc", "de", "fgh", "h", "e", "llo"};
//如果拷貝的長度在有效範圍1 ~ arr.length , 就拷貝指定的個數
//拷貝的長度 >  arr.length , 多餘用null佔位, 小於0就會報錯
String[] newArr = Arrays.copyOf(strArr, 2); //複製陣列
System.out.println(Arrays.toString(newArr));

String[] newArr2 = Arrays.copyOfRange(strArr, 2, 4); //區間複製,左開右閉
System.out.println(Arrays.toString(newArr2));

System.out.println(strArr.equals(newArr)); //判斷陣列的值是否相等

int[] arr2 = {10, 20, 30};
Arrays.fill(arr2, 40); // 陣列的填充
System.out.println(Arrays.toString(arr2));

List<int[]> list = Arrays.asList(arr2); //將陣列轉換成list
System.out.println(list.size());

System類

/**
 * The <code>System</code> class contains several useful class fields
 * and methods. It cannot be instantiated.
 *
 * <p>Among the facilities provided by the <code>System</code> class
 * are standard input, standard output, and error output streams;
 * access to externally defined properties and environment
 * variables; a means of loading files and libraries; and a utility
 * method for quickly copying a portion of an array.
 *
 * System類包含幾個有用的類欄位和方法。無法例項化。
 * System類提供的功能包括標準輸入,標準輸出和錯誤輸出流。 訪問外部定義的屬性和環境變數;一種載入檔案和庫的方法; 以及用於快速
 * 制陣列的一部分的實用方法。
 * @author  unascribed
 * @since   JDK1.0
 */
public final class System {
 public static void main(String[] args) {
        // arraycopy :複製陣列元素,比較適合底層呼叫,一般使用Arrays.copyOf完成複製陣列.
        int[] src = {1, 2, 3}; //源陣列
        int[] dest = new int[3];//目標陣列
        /**解讀
         * @param      src      源陣列
         * @param      srcPos   源陣列中的起始位置
         * @param      dest     目標陣列
         * @param      destPos  目標資料中的起始位置
         * @param      length   要複製的陣列元素的數量
         */
        System.arraycopy(src, 1, dest, 1, 2);
        System.out.print(Arrays.toString(dest));
        System.out.println();

        for (int i = 0; i < 10; i++) {
            if (i == 6) {
                System.exit(0); //退出程式
            }
            System.out.println(i);
        }

BigInteger/BigDecimal類

/**
 * Immutable arbitrary-precision integers.  All operations behave as if
 * BigIntegers were represented in two's-complement notation (like Java's
 * primitive integer types).  BigInteger provides analogues to all of Java's
 * primitive integer operators, and all relevant methods from java.lang.Math.
 * Additionally, BigInteger provides operations for modular arithmetic, GCD
 * calculation, primality testing, prime generation, bit manipulation,
 * and a few other miscellaneous operations.
 *
 * 不可變的任意精度整數,適合儲存比較大的整型
 */
public class BigInteger extends Number implements Comparable<BigInteger> {}

/**
 * Immutable, arbitrary-precision signed decimal numbers.  A
 * {@code BigDecimal} consists of an arbitrary precision integer
 * <i>unscaled value</i> and a 32-bit integer <i>scale</i>.  If zero
 * or positive, the scale is the number of digits to the right of the
 * decimal point.  If negative, the unscaled value of the number is
 * multiplied by ten to the power of the negation of the scale.  The
 * value of the number represented by the {@code BigDecimal} is
 * therefore <tt>(unscaledValue &times; 10<sup>-scale</sup>)</tt>.
 *
 * 不可變,任意精度的帶符號十進位制數字,適合儲存精度更高的浮點型(小數)
 */
public class BigDecimal extends Number implements Comparable<BigDecimal> {}
public class TestBig {
    public static void main(String[] args) {
        System.out.println("整數-------------------------------------------------------------------");
        //long num=855451236958545452125L;儲存不了
        BigInteger num1 = new BigInteger("855451236958545452125");
        System.out.println(num1);

        //運算方法
        BigInteger num2 = new BigInteger("41455288452565565656336655454588545");
        System.out.println(num1.add(num2)); //加
        System.out.println(num2.subtract(num1)); //減
        System.out.println(num1.multiply(num2)); //乘
        System.out.println(num2.divide(num1)); //除

        System.out.println("浮點數-------------------------------------------------------------------");
        //精度損失了
        double d1 = 4567888888888888888888888888888888888888222222222222222222222222222222222222228888888.23;
        System.out.println(d1);
        BigDecimal d = new BigDecimal("45678888888888888888888888888888888888882222222222222222222222222222222222222222222222222222222222222222222222222222288888888888888888888888888.23");
        BigDecimal d2 = new BigDecimal(33);
        System.out.println(d);
        System.out.println(d.add(d2)); //加
        System.out.println(d.subtract(d2)); //減
        System.out.println(d.multiply(d2)); //乘
        //沒有後面沒有引數,則會提示:ArithmeticException:Non-terminating decimal expansion; no exact representable decimal result.
        System.out.println(d.divide(d2, BigDecimal.ROUND_CEILING)); //除
    }
}

日期類

使用的時候去查API手冊即可!

第一代日期類

public class TestDate {
    public static void main(String[] args) throws ParseException {
        Date date= new Date();
        System.out.println(date);
        System.out.println(date.getTime()); //獲取某個時間對應的毫秒數

        //使用SimpleDateFormat進行格式化輸出, "yyyy-MM-dd HH:mm:ss E" 各個字母是格式化符合,是規定好的
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
        System.out.println(dateFormat.format(date));

        //通過一個毫秒,得到對應的日期
        Date d2 = new Date(1606924829078L);
        System.out.println(dateFormat.format(d2));

        //將一個String 格式化轉成Date物件,s格式需要和dateFormat格式匹配,否則ParseException
        String s="2020-02-03 00:01:40 星期四";
        Date format = dateFormat.parse(s);
        System.out.println(format.getTime());
    }
}

格式化日期要求的字母格式

格式化日期的字母格式

第二代日期類

第二代日期類,主要就是 Calendar類(日曆)

/**
 * The <code>Calendar</code> class is an abstract class that provides methods
 * for converting between a specific instant in time and a set of {@link
 * #fields calendar fields} such as <code>YEAR</code>, <code>MONTH</code>,
 * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, and so on, and for
 * manipulating the calendar fields, such as getting the date of the next
 * week. An instant in time can be represented by a millisecond value that is
 * an offset from the <a name="Epoch"><em>Epoch</em></a>, January 1, 1970
 * 00:00:00.000 GMT (Gregorian).
 *
 *  Calendar類是一個抽象類,提供用於在特定時間點和一組calendar fields例如YEAR ,MONTH ,DAY_OF_MONTH ,HOUR等)之間
 *	進行轉換的方法,以及用於處理日曆欄位(例如獲取下一星期日期)的方法。時間的瞬間可以用毫秒值表示
 *	該值是從1970年1月1日格林尼治標準時間(Gregorian)到Epoch的偏移量。
 *
 *	Calendar提供了一個類方法getInstance ,用於獲取這種型別的通常有用的物件。 
 *	Calendar的getInstance方法返回一個Calendar物件,該物件的日曆欄位已使用當前日期和時間初始化:
 *	Calendar rightNow = Calendar.getInstance();
 */
public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar>
public class TestCalendar {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.getClass());

        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int date = calendar.get(Calendar.DATE);
        int hour = calendar.get(Calendar.HOUR);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        System.out.printf("%d-%d-%d %d:%d:%d 星期%d", year, month, date, hour, minute, second, week);
        
        calendar.set(Calendar.YEAR,2000);
        calendar.set(Calendar.MONTH,2);
        calendar.set(Calendar.DATE,28);
        int year2 = calendar.get(Calendar.YEAR);
        int month2 = calendar.get(Calendar.MONTH);
        int date2 = calendar.get(Calendar.DATE);
        System.out.printf("%d-%d-%d", year2, month2, date2);//原日期會變
    }
}

第三代日期類

前兩代日期類都有不足的地方,JDK 1.0中包含了一個java.util.Date類,但是它的大多數方法已經在JDK 1.1引入Calendar類之後被棄用了。而Calendar並不比Date好多少。

  • 可變性 : 像日期和時間這樣的類應該是不可變的。

  • 偏移性 : Date中 的年份是從1900開始的,而月份都從0開始。

  • 格式化 : 格式化只對Date有用,Calendar則不行。

第三代日期類常見方法:LocalDate(日期)、LocalTime(時間)、LocalDateTime(日期時間)

public class TestDate03 {
    public static void main(String[] args) {
        //now()-:獲取當前的日期,時間,日期+時間
        LocalDate date= LocalDate.now(); //獲取當前的日期
        System.out.println(date);
        LocalTime time=LocalTime.now();
        System.out.println(time); //獲取當前的時間
        LocalDateTime dateTime=LocalDateTime.now();//,獲取當前日期+時間
        System.out.println(dateTime);

        //of():設定指定的日期,時間,日期+時間
        LocalDate date1=LocalDate.of(2010,5,25);
        LocalTime time1=LocalTime.of(10,15,25);
        LocalDateTime dateTime1=LocalDateTime.of(date1,time1);
        System.out.println(dateTime1);

        System.out.println(dateTime.getYear());
        System.out.println(dateTime.getMonth());
        System.out.println(dateTime.getMonthValue());
        System.out.println(dateTime.getDayOfMonth());
        System.out.println(dateTime.getDayOfWeek());
        System.out.println(dateTime.getHour());
        System.out.println(dateTime.getMinute());
        System.out.println(dateTime.getSecond());

        LocalDateTime localDateTime=dateTime.withYear(1998); //with:設定日期
        System.out.println(localDateTime);
        System.out.println(dateTime); //原日期不會跟著新日期改動就變化

        LocalDateTime plusYears = localDateTime.plusYears(10); //plus:加操作
        System.out.println(plusYears);
        LocalDateTime minusMonths = localDateTime.minusMonths(6); //minus:減操作
        System.out.println(minusMonths);
        //API還有很多方法
    }
}

還是那句話,具體的詳細資訊還是要通過原始碼或者API幫助文件查詢,經常用的API用著用著就熟練了,不常用的檢視手冊!

相關文章