JavaAPI-工具類

java提供了一系列的工具類,咱們應用的時候能夠訪問它們的屬性和方法,可是工具類不少,記住經常使用的便可!使用的時候就去API幫助文檔手冊查找,有離線的和在線版本的,離線的百度搜索一下都能找到java

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

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

Object

以前咱們說過Object是全部類的根類,那麼說具體的工具類以前,咱們先說一下Objectwindows

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

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就引進了包裝類安全

基本數據類型 包裝類 父類
byte Byte Number------->Object
boolean Boolean Object
short Short Number------->Object
char Character Object
int Integer Number------->Object
long Long Number------->Object
float Float Number------->Object
double Double Number------->Object

Integer

拿Integer作案例來進行講解,此類掌握了以後其它的包裝類大同小異多線程

從上面API幫助文檔手冊能夠看出幾個信息,全部的類均可以從 API幫助文檔手冊上查看!oracle

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

  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還有不少方法
    }
}

文件類

File

/**
 * An abstract representation of file and directory pathnames.
 *
 * 文件和目錄路徑名的抽象表示,也就是把文件和文件夾封裝成了一個對象,能夠用程序操做它
 */
 public class File
    implements Serializable, Comparable<File>
{
public class TestFile {
    public static void main(String[] args) throws IOException {
        /**建立文件對象File
         * new File(String pathname)             根據路徑構建一個File對象
         * new File(File parent,String child):  根據父目錄文件+子路徑構建
         * new File(String parent,String child)  根據父目錄+子路徑構建
         */
        File file1 = new File("E:\\testA.txt"); //路徑分隔符:\\或者/,是Windows系統私有
        File file2 = new File("E:\\", "testB.txt");
        File parent = new File("E:\\");
        File file3 = new File(parent, "testC.txt");
        /**
         * File.separator屬性幫咱們獲取當前操做系統的路徑拼接符號
         * windows系統中,默認用"\"做爲路徑分隔符
         * unix和Linux系統中,默認用"/"做爲路徑分隔符
         */
        File file = new File("E:" + File.separator + "testD.txt");

        //文件經常使用方法
        if (file1.exists()) { //exists():判斷文件是否存在
            file1.delete(); //delete():刪除文件
        } else {
            file1.createNewFile();  //createNewFile():建立文件
        }

        System.out.println(file1.canRead()); //文件是否可讀
        System.out.println(file1.canWrite()); //文件是否可寫
        System.out.println(file1.getName()); //獲取文件名字
        System.out.println(file1.getParent()); //獲取上一級目錄
        System.out.println(file1.length()); //獲取文件的大小
        System.out.println(file1.isDirectory()); //是否目錄
        System.out.println(file1.isFile()); //是否文件
        System.out.println(file1.isHidden()); //是否隱藏
        System.out.println(file1.getPath()); //獲取相對路徑,相對於一個參照物的路徑
        System.out.println(file1.getAbsolutePath()); //獲取絕對路徑,文件的完整路徑

        File way = new File("a/b/c/test.txt");
        System.out.println("絕對路徑:" + way.getAbsolutePath());
        System.out.println("相對路徑:" + way.getPath()); //此參照的是當前工做目錄

        
        //目錄經常使用方法
        File path = new File("E:\\a");
        if (path.exists()) {
            path.delete(); //只會刪除空的單層目錄
        } else {
            path.mkdir(); //只會建立單層目錄
        }
        File path2 = new File("E:/a/b/c");
        path2.mkdirs(); //能夠建立多層目錄

        //獲取
        String[] list = path.list();
        for (String s : list) {
            System.out.println(s);
        }
        System.out.println("----------------");
        for (File listFile : path.listFiles()) {
            System.out.println(listFile + "," );
        }

      //文件具體數據內容的操做是以io流方式操做
    }
}

仍是那句話,具體的詳細信息仍是要經過源碼或者API幫助文檔查找,常常用的API用着用着就熟練了,不經常使用的查看手冊!

相關文章
相關標籤/搜索