【Java】常用的類類們

學習網站:https://www.shiyanlou.com/


一、Arrays

Arrays 類包含用於操作數組的各種方法(例如排序和搜索)。還包含一個靜態工廠,允許將數組轉爲 List。

Arrays常用方法:

方法 描述
<T> List<T> asList(T... a) 返回由指定數組構造的List
void sort(Object[] a) 對數組進行排序
void fill(Object[] a, Object val) 爲數組的所有元素都賦上相同的值
boolean equals(Object[] a, Object[] a2) 檢查兩個數組是否相等
int binarySearch(Object[] a, Object key) 對排序後的數組使用二分法查找數據

使用示例:

import java.util.Arrays;
import java.util.Random;

public class ArraysDemo {
    public static void main(String[] args) {
        int[] arr = new int[10];

        //將數組元素都設爲9
        Arrays.fill(arr, 9);
        System.out.println("fill:" + Arrays.toString(arr));

        Random random = new Random();
        for (int i = 0; i < arr.length; i++) {
            //使用100以內的隨機數賦值數組
            arr[i] = random.nextInt(101);
        }
        //重新賦值後的數組
        System.out.println("重新賦值:" + Arrays.toString(arr));

        //將索引爲5的元素設爲50
        arr[5] = 50;

        //排序
        Arrays.sort(arr);
        //排序後的數組
        System.out.println("sort排序後:" + Arrays.toString(arr));

        //查找50的位置
        int i = Arrays.binarySearch(arr, 50);
        System.out.println("值爲50的元素索引:"+i);

        //複製一份新數組
        int[] newArr = Arrays.copyOf(arr, arr.length);
        //比較
        System.out.println("equals:"+Arrays.equals(arr, newArr));
    }
}

二、StringBuilder

StringBuilder 類是可變的。它是 String 的對等類,它可以增加和編寫字符的可變序列,並且能夠將字符插入到字符串中間或附加到字符串末尾(當然是不用創建其他對象的)

構造方法

構造方法 說明
StringBuilder() 構造一個其中不帶字符的 StringBuilder,其初始容量爲 16 個字符
StringBuilder(CharSequence seq) 構造一個 StringBuilder,它包含與指定的 CharSequence 相同的字符
StringBuilder(int capacity) 構造一個具有指定初始容量的 StringBuilder
StringBuilder(String str) 並將其內容初始化爲指定的字符串內容

常用方法

方法 返回值 功能描述
insert(int offsetm,Object obj) StringBuilder 在 offsetm 的位置插入字符串 obj
append(Object obj) StringBuilder 在字符串末尾追加字符串 obj
length() int 確定 StringBuilder 對象的長度
setCharAt(int index,char ch) void 使用 ch 指定的新值設置 index 指定的位置上的字符
toString() String 轉換爲字符串形式
reverse() StringBuilder 反轉字符串
delete(int start, int end) StringBuilder 刪除調用對象中從 start 位置開始直到 end 指定的索引(end-1)位置的字符序列
replace(int start, int end, String str) StringBuilder 使用一組字符替換另一組字符。將用替換字符串從 start 指定的位置開始替換,直到 end 指定的位置結束

使用示例:

public class StringBuilderTest {

    public static void main(String[] args){
        //定義和初始化一個StringBuilder類的字串s
        StringBuilder s = new StringBuilder("I");
        //在s後面添加字串" java"
        s.append(" java");
        //在s[1]的位置插入字串
        s.insert(1, " love");
        String t = s.toString(); //轉爲字符串
        System.out.println(t);
    }
}

三、Calendar

允許用年、月、日、時、分、秒來解釋日期

Calendar 類是一個抽象類,它完成 Date 類與普通日期表示法之間的轉換,而我們更多的是使用 Calendar 類的子類 GregorianCalendar 類。它實現了世界上普遍使用的公曆系統。當然我們也可以繼承 Calendar 類,然後自己定義實現日曆方法。

先來看一看 GregorianCalendar 類的構造函數:

構造方法 說明
GregorianCalendar() 創建的對象中的相關值被設置成指定時區,缺省地點的當前時間,即程序運行時所處的時區、地點的當前時間
GregorianCalendar(TimeZone zone) 創建的對象中的相關值被設置成指定時區 zone,缺省地點的當前時間
GregorianCalendar(Locale aLocale) 創建的對象中的相關值被設置成缺省時區,指定地點 aLocale 的當前時間
GregorianCalendar(TimeZone zone,Locale aLocale) year - 創建的對象中的相關值被設置成指定時區,指定地點的當前時間

PS:

TimeZone 是 java.util 包中的一個類,其中封裝了有關時區的信息。每一個時區對應一組 ID。

類 TimeZone 提供了一些方法完成時區與對應 ID 兩者之間的轉換。

例如:

//太平洋時區的 ID 爲 PST
TimeZone tz0 = TimeZone.getTimeZone("PST")
//getDefault()可以獲取主機所處時區的對象
TimeZone tz1 = TimeZone.getDefault()

Locale 只是一種機制,它用來標識一個特定的地理、政治或文化區域獲取一個 Locale 對象的構造方法:

//調用Locale類的構造方法
Locale l0 = new Locale(String language)
Locale l1 = new Locale(String language, String country)
Locale l2 = new Locale(String languge, String country, String variant)

//調用Locale類中定義的常量
Locale  l1 = Locale.CHINA

使用示例:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CalendarDemo {
    public static void main(String[] args) {
        System.out.println("完整顯示日期時間:");
        // 字符串轉換日期格式
        DateFormat fdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = fdate.format(new Date());
        System.out.println(str);

        // 創建 Calendar 對象
        Calendar calendar = Calendar.getInstance();
        // 初始化 Calendar 對象,但並不必要,除非需要重置時間
        calendar.setTime(new Date());

        // 顯示年份
        System.out.println("年: " + calendar.get(Calendar.YEAR));

        // 顯示月份 (從0開始, 實際顯示要加一)
        System.out.println("月: " + calendar.get(Calendar.MONTH));


        // 當前分鐘數
        System.out.println("分鐘: " + calendar.get(Calendar.MINUTE));

        // 今年的第 N 天
        System.out.println("今年的第 " + calendar.get(Calendar.DAY_OF_YEAR) + "天");

        // 本月第 N 天
        System.out.println("本月的第 " + calendar.get(Calendar.DAY_OF_MONTH) + "天");

        // 3小時以後
        calendar.add(Calendar.HOUR_OF_DAY, 3);
        System.out.println("三小時以後的時間: " + calendar.getTime());
        // 格式化顯示
        str = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendar.getTime());
        System.out.println(str);

        // 重置 Calendar 顯示當前時間
        calendar.setTime(new Date());
        str = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendar.getTime());
        System.out.println(str);

        // 創建一個 Calendar 用於比較時間
        Calendar calendarNew = Calendar.getInstance();

        // 設定爲 5 小時以前,後者大,顯示 -1
        calendarNew.add(Calendar.HOUR, -5);
        System.out.println("時間比較:" + calendarNew.compareTo(calendar));

        // 設定7小時以後,前者大,顯示 1
        calendarNew.add(Calendar.HOUR, +7);
        System.out.println("時間比較:" + calendarNew.compareTo(calendar));

        // 退回 2 小時,時間相同,顯示0
        calendarNew.add(Calendar.HOUR, -2);
        System.out.println("時間比較:" + calendarNew.compareTo(calendar));

        // calendarNew創建時間點
        System.out.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendarNew.getTime()));
        // calendar創建時間點
        System.out.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendar.getTime()));
        System.out.println("時間比較:" + calendarNew.compareTo(calendar));
    }
}

四、Date

Date 類表示日期和時間,裏面封裝了操作日期和時間的方法。Date 類經常用來獲取系統當前時間

來看看類 Date 中定義的未過時的構造方法:

構造方法 說明
Date() 構造一個 Date 對象並對其進行初始化以反映當前時間
Date(long date) 構造一個 Date 對象,並根據相對於 GMT 1970 年 1 月 1 日 00:00:00 的毫秒數對其進行初始化

使用示例

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDemo {
    public static void main(String[] args) {
        String strDate, strTime;
        Date objDate = new Date();
        System.out.println("今天的日期是:" + objDate);

        long time = objDate.getTime();
        System.out.println("自1970年1月1日起以毫秒爲單位的時間(GMT):" + time);
        
        strDate = objDate.toString();
        
        //提取 GMT 時間
        strTime = strDate.substring(11, (strDate.length() - 4));
        
        //按小時、分鐘和秒提取時間
        strTime = "時間:" + strTime.substring(0, 8);
        System.out.println(strTime);
       
        //格式化時間
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(formatter.format(objDate));
    }
}

五、Math

Math 類在 java.lang 包中,包含用於執行基本數學運算的方法,如初等指數、對數、平方根和三角函數。

常見方法:

方法 返回值 功能描述
sin(double numvalue) double 計算角 numvalue 的正弦值
cos(double numvalue) double 計算角 numvalue 的餘弦值
acos(double numvalue) double 計算 numvalue 的反餘弦
asin(double numvalue) double 計算 numvalue 的反正弦
atan(double numvalue) double 計算 numvalue 的反正切
pow(double a, double b) double 計算 a 的 b 次方
sqrt(double numvalue) double 計算給定值的正平方根
abs(int numvalue) int 計算 int 類型值 numvalue 的絕對值,也接收 long、float 和 double 類型的參數
ceil(double numvalue) double 返回大於等於 numvalue 的最小整數值
floor(double numvalue) double 返回小於等於 numvalue 的最大整數值
max(int a, int b) int 返回 int 型 a 和 b 中的較大值,也接收 long、float 和 double 類型的參數
min(int a, int b) int 返回 a 和 b 中的較小值,也可接受 long、float 和 double 類型的參數
rint(double numvalue) double 返回最接近 numvalue 的整數值
round(T arg) arg 爲 double 時返回 long,爲 float 時返回 int 返回最接近arg的整數值
random() double 返回帶正號的 double 值,該值大於等於 0.0 且小於 1.0

使用示例:

public class MathDemo {
    public static void main(String[] args) {
        System.out.println(Math.abs(-12.7));
        System.out.println(Math.ceil(12.7));
        System.out.println(Math.rint(12.4));
        System.out.println(Math.random());
        System.out.println("sin30 = " + Math.sin(Math.PI / 6));
        // 計算30°的正弦值,參數是用弧度表示的角,即π的六分之一
        System.out.println("cos30 = " + Math.cos(Math.PI / 6));
        // 計算30°的餘弦值,這些計算三角函數的方法,其參數和返回值的類型都爲double
        System.out.println("tan30 = " + Math.tan(Math.PI / 6));
        // 計算30°的正切值
    }
}

六、System

System 類提供了以下功能:

  • 標準輸入,標準輸出和錯誤輸出流;
  • 訪問外部定義的屬性和環境變量;
  • 加載文件和庫的方法;
  • 以及用於快速複製數組的實用方法。

System 不可以被實例化,只可以使用其靜態方法。

//從指定的源數組中複製一個數組,從源數組指定的位置開始,到目標數組指定的位置
public static void arraycopy(Object src,int srcPos, Object dest,int desPos,int length) 
//返回以毫秒爲單位的當前時間(從1970年到現在的毫秒數)
public static long currentTimeMillis()  
//終止當前正在運行的Java虛擬機,status爲 0時退出
public static void exit(int status)  
//  運行垃圾收集器
public static void gc() 
// 取得當前系統的全部屬性
public static Properties getProperties()
//獲取指定鍵的系統屬性
public static String  getProperty(String key) 

下一步

使用示例:

import java.util.Arrays;

public class SystemDemo {
    public static void main(String[] args) {
        int[] a = {7, 8, 9, 10, 11};
        int[] b = {1, 2, 3, 4, 5, 6};
        //從數組a的第二個元素開始,複製到b數組的第三個位置 複製的元素長度爲3
        System.arraycopy(a, 1, b, 2, 3);
        //輸出結果
        System.out.println(Arrays.toString(b));
        System.out.println("當前時間:" + System.currentTimeMillis());
        System.out.println("java版本信息:" + System.getProperty("java.version"));
        //運行垃圾收集器
        System.gc();
        //退出
        System.exit(0);
    }
}

七、Random

Random 類用於生成僞隨機數流,在java.util包下。

使用示例:

import java.util.Random;

public class RandomDemo {
    public static void main(String[] args) {
        Random random = new Random();
        //隨機生成一個整數 int範圍
        System.out.println(random.nextInt());
        //生成 [0,n] 範圍的整數  設n=100
        System.out.println(random.nextInt(100 + 1));
        //生成 [0,n) 範圍的整數  設n=100
        System.out.println(random.nextInt(100));
        //生成 [m,n] 範圍的整數  設n=100 m=40
        System.out.println((random.nextInt(100 - 40 + 1) + 40));
        //隨機生成一個整數 long範圍
        System.out.print(random.nextLong());
        //生成[0,1.0)範圍的float型小數
        System.out.println(random.nextFloat());
        //生成[0,1.0)範圍的double型小數
        System.out.println(random.nextDouble());
    }
}

 

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