Java基礎進階_day06_(Object,常用類,包裝類,正則表達式)

Java基礎進階_day06_(Object,常用類,包裝類,正則表達式)

1. Object類

Object 是類層次結構的根類.每個類都使用 Object作爲超類.所有對象(包括數組)都實現這個類的方法.
所有的類都直接過間接繼承Object類.

1.1 Object類的方法

public int hashCode():返回該對象的哈希碼值.
    哈希值是根據哈希算法計算出來的值,這個值跟地址值有關,但是不是實際地址值.
public final Class<?> getClass():返回此Object的運行時類,返回的Class對象是由所表示類的static synchronized方法鎖定的對象.
        Class類中的方法:
            public String getName():以 String的形式返回此Class對象所表示的實體(類,接口,數組類,基本類型或 void)名稱.
public String toString():返回該對象的字符串表示.
    子類一般重寫該方法(自動生成即可).
    直接輸出一個對象名稱,其實默認調用了該對象的toString()方法.
public boolean equals(Object obj):指示其他某個對象是否與此對象"相等".
    Object類中默認比較的是兩個對象的地址值是否相等,子類如果想要比較成員屬性是否相等需要將該方法重寫(一般自動生成).
protected void finalize() throws Throwable:當垃圾回收器確定不存在對該對象的更多引用時,
    由對象的垃圾回收器調用此方法.子類重寫finalize方法,以配置系統資源或執行其他清除.子類一般不進行重寫.
protected Object clone() throws CloneNotSupportedException:創建並返回此對象的一個副本.
    Object類本身不實現接口Cloneable,所以在類爲Object的對象上調用clone方法將會導致在運行時拋出異常;
    子類重寫該方法需要實現Cloneable接口(Cloneable接口只是一個是否能被克隆的標識,其本身沒有任何屬性及方法).

1.2 ==和equals()的區別:

# A:==
 * 基本類型:比較的是值是否相同
 * 引用類型:比較的是地址值是否相同
# B:equals()
 * 只能比較引用類型。默認情況下,比較的是地址值是否相同。
 * 但可以根據需要重寫該方法。

2. 常用類

2.1 Math類

Math類: Math類包含用於執行基本數學運算的方法,如初等指數,對數,平方根和三角函數.是一個工具類.

2.1.1 Math類的成員屬性
// 成員屬性: Math類中的屬性均爲靜態常量.
public static final double E:比任何其他值都更接近 e(即自然對數的底數)的 double值.
public static final double PI:比任何其他值都更接近 pi(即圓的周長與直徑之比)的 double值.
2.1.2 Math類中的成員方法
public static int abs(int a):返回 int 值的絕對值.
public static double ceil(double a):返回最小的(最接近負無窮大)double值,該值大於等於參數,並等於某個整數.
public static double floor(double a):返回最大的(最接近正無窮大)double值,該值小於等於參數,並等於某個整數.
public static double max(double a,double b):返回兩個 double值中較大的一個.
public static int min(int a,int b):返回兩個 int值中較小的一個.
public static double pow(double a,double b):返回第一個參數的第二個參數次冪的值.
public static double random():返回帶正號的 double值,該值大於等於0.0且小於1.0.
public static int round(float a):返回最接近參數的int.
public static double sqrt(double a):返回正確舍入的double值的正平方根.
2.1.3 案例代碼
public class MyMathDemo {
    public static void main(String[] args) {
        // E和PI的值
        System.out.println("E:"+Math.E+",PI:"+Math.PI);
        // 求絕對值
        System.out.println(Math.abs(-123));
        // 向上取整
        System.out.println(Math.ceil(1.999));
        // 向下取整
        System.out.println(Math.floor(1.999));
        // 求兩個數的最大值
        System.out.println(Math.max(2, 5));
        // 求兩個數的最小值
        System.out.println(Math.min(34, 34));
        // 求第一個數的第二個數的次冪
        System.out.println(Math.pow(2,63));
        // 隨機數範圍是[0,1)浮點數
        System.out.println(Math.random());
        // 四捨五入
        System.out.println(Math.round(3.6));
        // 求一個數的正的平方根
        System.out.println(Math.sqrt(4.5));
        // 生成指定範圍內的整形數的隨機數
        System.out.println(myRandom(1, 100));
    }
    /**
     * 生成指定範圍內的整形數的隨機數
     * @param start 包含
     * @param end 包含
     * @return
     */
    public static int myRandom(int start, int end) {
        return (int)(Math.random()*(end - start + 1) + start);
    }
}

2.2 System類

System類:包含一些有用的類字段和方法,它不能被實例化.

2.2.1 System類的成員方法
public static void gc():運行垃圾回收器. 調用此方法時,jvm默認的會調用類的finalize方法進行垃圾回收,Object類定義了這個方法,子類需要重寫該方法.
public static void exit(int status):終止當前正在運行的Java虛擬機.參數用作狀態碼,非0的狀態碼錶示異常終止.
public static long currentTimeMillis():返回以毫秒爲單位的當前時間.
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length): 從指定源數組中複製一個數組,複製從指定的位置開始,到目標數組的指定位置結束.
public static Properties getProperties():獲取當前的系統屬性。
public static String getProperty(String key):獲取指定鍵指示的系統屬性.
2.2.2 案例代碼
public class MySystemDemo {
    public static void main(String[] args) {
        // 調用系統的垃圾回收器
        Person p = new Person("somnus");
        System.out.println(p); // Person [name=somnus]
        p = null;
        System.gc(); // jvm回收垃圾:Person [name=somnus]
        // exit方法,退出jvm
        System.out.println("hello");
        // System.exit(0);
        // System.out.println("world"); // 不會執行
        // currentTimeMillis獲取當前時間,以毫秒錶示
        // 用於統計程序運行時間
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            // System.out.println(i);
        }
        long end = System.currentTimeMillis();
        System.out.println("程序運行時間:"+ (end - start));
        // arraycopy方法
        int[] arr = {1,2,3,4,5,6};
        int[] arr1 = {7,8,9,10,11,12};
        System.arraycopy(arr, 1, arr1, 2, 3);
        System.out.println(Arrays.toString(arr));
        System.out.println(Arrays.toString(arr1));
        // 獲取指定的系統屬性,可以查詢API
        System.out.println(System.getProperty("user.name"));
        System.out.println(System.getProperty("user.home"));
        System.out.println(System.getProperty("user.dir"));
        System.out.println(System.getProperty("os.name"));
    }
}
// 定義標準的類
class Person {
    private String name;
    public Person() {
        super();
    }
    public Person(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    // 重寫父類(Object)的toString方法
    @Override
    public String toString() {
        return "Person [name=" + name + "]";
    }
    // 重寫父類的finalize方法,用於垃圾回收
    @Override
    protected void finalize() throws Throwable {
        System.out.println("jvm回收垃圾:" + this);
        super.finalize();
    }
}

2.3 Random類

Random類是用於生成僞隨機數的流。

2.3.1 Random類構造方法
public Random():創建一個新的隨機數生成器. 此構造方法將隨機數生成器的種子設置爲某個值(當前時間的毫秒).
public Random(long seed):使用單個long種子創建一個新的隨機數生成器.
// 兩個構造方法的區別: 給出種子seed後,每次(重新運行)生成的隨機數相同.
2.3.2 Random類成員方法
public int nextInt():返回下一個隨機數.
public int nextInt(int n)返回一個在 [0,n)範圍內的隨機數.
2.3.3 案例代碼
public class MyRandomDemo {
    public static void main(String[] args) {
        Random r = new Random();
        System.out.println(r.nextInt());
        // 每次重新運行時的結果相同
        Random rr =new Random(1213);
        System.out.println(rr.nextInt());
        System.out.println(rr.nextInt());
        System.out.println(rr.nextInt());
    }
}

2.4 Date

Date類:表示時間,精確到毫秒.

2.4.1 Date類構造方法
public Date():分配Date對象並初始化此對象,以表示分配它的時間(精確到毫秒). 空參構造方法獲取的是當前系統的時間.
public Date(long date):使用給定毫秒時間值構造一個 Date對象. 有參構造方法是在曆元時間基礎上進行日期推算.
2.4.2 Date類成員方法
public long getTime():返回自1970年1月1日00:00:00 GMT以來此Date對象表示的毫秒數.
// 獲取毫秒的時間方法:
// System.currentTimeMillis()也可以獲取毫秒數.
// Calendar類的getTime()方法和getTimeInMillis()方法獲取毫秒數時間.
public void setTime(long time):設置此 Date對象,以表示1970年1月1日 00:00:00 GMT以後time毫秒的時間點.
2.4.3 案例代碼
public class MyDateDemo {
    public static void main(String[] args) {
        /*
         * 構造方法
         */
        Date d = new Date();
        System.out.println(d); // Tue Mar 28 18:59:49 CST 2017
        long date = 3600*1000;
        Date d1 = new Date(System.currentTimeMillis()); 
        System.out.println(d1); // Tue Mar 28 18:59:49 CST 2017
        Date d2 = new Date(date); 
        System.out.println(d2); // Thu Jan 01 09:00:00 CST 1970
        // 當Date的構造參數爲負數時,是在曆元時間基礎上向前推進
        Date d4 = new Date(-1000L);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        System.out.println("d4:"+sdf.format(d4)); // 1970年01月01日 07:59:59
        /*
         * 成員方法
         */
        Date d3 = new Date();
        System.out.println(d3.getTime()); // 1490699238339
        d3.setTime(date);
        System.out.println(d3); // Thu Jan 01 09:00:00 CST 1970
    }
}

2.5 DateFormat抽象類

DateFormat抽象類:是日期/時間格式化子類的抽象類,它以與語言無關的方式格式化並解析日期或時間.

2.5.1 日期和字符串間的轉換
# Date-->String  日期格式化
# String-->Date  解析文本
# DateFormat類是一個抽象類,其有一個子類SimpleDateFormat是具體類,使用時用的子類的對象.
2.5.2 SimpleDateFormat類

構造方法

// SimpleDateFormat類
public SimpleDateFormat():用默認的模式和默認語言環境的日期格式符號構造 SimpleDateFormat.
public SimpleDateFormat(String pattern):用給定的模式和默認語言環境的日期格式符號構造SimpleDateFormat.
// DateFormat類
public final String format(Date date):將一個Date格式化爲日期/時間字符串.
public Date parse(String source) throws ParseException:從給定字符串的開始解析文本,以生成一個日期.此方法處理的字符串必須和SimpleDateFormat創建對象時使用的格式匹配.
2.5.3 案例代碼
public class MyDateFormatDemo {
    public static void main(String[] args) throws ParseException {
        // 將日期格式爲默認的字符串格式
        SimpleDateFormat sdf = new SimpleDateFormat();
        Date d = new Date();
        System.out.println("格式化前的日期:"+d);
        String date = sdf.format(d);
        System.out.println("格式化後的日期:"+date); // 默認格式17-3-28 下午7:32
        // 將日期格式爲指定的字符串格式
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss E");
        Date d2 = new Date();
        System.out.println("格式化前的日期:"+d2);
        String date2 = sdf2.format(d);
        System.out.println("格式化後的日期:"+date2); // 輸出的指定格式2017年03月28日  19:32:59

        // 將字符串解析爲日期
        // date3格式必須和SimpleDateFormat構造的參數格式嚴格匹配(空格也不能多)
        String date3 = "2015-02-28 19:19:19";
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d4 = sdf3.parse(date3);
        System.out.println(d4); // Sat Feb 28 19:19:19 CST 2015
}

2.6 Calendar抽象類

Calendar抽象類:是一個抽象類,它爲特定瞬間與一組諸如YEAR等日曆字段之間的轉換提供了一些方法,併爲操作日曆字段提供了一些方法.

2.6.1 Calendar類的子類
# Calendar是一個抽象類,通過創建其子類的對象進行日期的操作.
# Calendar的getInstance方法返回一個Calendar對象,其日曆字段已由當前日期和時間初始化:
    Calendar rightNow = Calendar.getInstance();
    rightNow中存儲了當前時間的所有與時間相關的字段值,直接輸出結果如下:
    java.util.GregorianCalendar[time=1490768748872,YEAR=2017,MONTH=2,,DAY_OF_MONTH=29...]
2.6.1 Calendar類的成員方法
// 成員方法:日曆類是將日曆的所有字段都存儲好了,需要什麼字段的時間的信息,直接通過get方法獲取.
public int get(int field):返回給定日曆字段的值.日曆類中的所有字段均爲靜態常量,需要哪個字段的信息,參數就是對應的字段值.
2.6.2 Calendar子類的方法
public abstract void add(int field,int amount):根據日曆的規則,爲給定的日曆字段添加或減去指定的時間量。
public final void set(int year,int month,int date):設置日曆字段 YEAR,MONTH和DAY_OF_MONTH的值.
public final Date getTime():返回一個表示此Calendar時間值(從曆元至現在的毫秒偏移量)的Date對象.
public long getTimeInMillis():返回此 Calendar的時間值,以毫秒爲單位.
// 注意事項:Calendar類的月是從0開始算起的.(0月代表1月)
2.6.3 案例代碼
public class MyCalendarDemo {
    public static void main(String[] args) {
        // 其日曆字段已由當前日期和時間初始化: 
        // 返回的是Calendar子類的對象
        Calendar rightNow = Calendar.getInstance();
        System.out.println(rightNow); // java.util.GregorianCalendar[YEAR=2017,MONTH=2,,DAY_OF_MONTH=29...]
        int year = rightNow.get(Calendar.YEAR);
        int month = rightNow.get(Calendar.MONTH);
        int day = rightNow.get(Calendar.DAY_OF_MONTH);
        System.out.println(year+"年"+month+"月"+day+"日"); // 2017年2月28日
        // add方法
        rightNow.add(Calendar.YEAR, -5); // 當前年份減去5年
        rightNow.add(Calendar.MONTH, -3); // 當前月份減去2個月
        rightNow.add(Calendar.DAY_OF_MONTH, -5); // 當前天數減去5天
        int year1 = rightNow.get(Calendar.YEAR);
        int month1 = rightNow.get(Calendar.MONTH);
        int day1 = rightNow.get(Calendar.DAY_OF_MONTH);
        System.out.println(year1+"年"+month1+"月"+day1+"日"); // 2012年0月23日
        // set方法
        rightNow.set(2018, 11, 28);
        int year2 = rightNow.get(Calendar.YEAR);
        int month2 = rightNow.get(Calendar.MONTH);
        int day2 = rightNow.get(Calendar.DAY_OF_MONTH);
        System.out.println(year2+"年"+month2+"月"+day2+"日"); // 2018年11月28日
        // getTime和getTimeInMillis方法
        System.out.println(rightNow.getTime()); // Fri Dec 28 20:38:56 CST 2018
        System.out.println(rightNow.getTimeInMillis()); // 1546000736997
        method(2016);
    }
    /**
     * 獲取任意一年2月份有多少天
     */
    public static void method(int year) {
        Calendar c = Calendar.getInstance();
        // 方式1,獲取該年份的2月第1天,和3月份的第1天,然後獲取各自時間的毫秒,再計算
        // 設置時間爲2月份的第1天
        c.set(year, 1, 1);
        System.out.println(c.get(Calendar.YEAR)+".."+c.get(Calendar.MONTH)+".."+c.get(Calendar.DATE));
        long forMonthDay = c.getTimeInMillis() / 1000 / 60 / 60 / 24;
        // 設置時間爲3月份的第1天
        c.set(year, 2, 1);
        long bacMonthDay = c.getTimeInMillis() / 1000 / 60 / 60 / 24;
        System.out.println(bacMonthDay-forMonthDay);
        // 方式2,獲取該年的3月份的第1天,然後將日期向前推1天,輸出改天即可
        c.set(year, 2, 1);
        c.add(Calendar.DATE, -1);
        System.out.println(c.get(Calendar.DATE));
    }
}

3. 基本數據類型的包裝類

基本數據類型的包裝類型:一般用包裝類進行基本數據類型與字符串間的轉換.
基本數據類型與對應的包裝類

byte short int long float double char boolean
Byte Short Integer Long Float Double Character Boolean

3.1 基本數據類型與字符串間的轉換

# 基本數據類型-->String
    public static String valueOf(int i)
# String-->基本數據類型
    public static int parseInt(String s)

3.2 注意事項

# 注意事項: 包裝類都有自動封箱和自動拆箱
    例如:
    Integer i = 4; // 自動裝箱,i是應用類型的變量
    i += 4; // 自動拆箱
# Integer類型變量賦值時需注意:
  * Integer中有個byte類型(-128~127)的緩衝池.直接使用賦值的方式時,如果數值在byte的取值範圍內,是直接從byte緩衝池中返回該值,不會創建對象;
  * 如果不在byte的緩衝池中,則會通過new Integer(i)的方式創建一個對象並返回.
  * Integer i1 = 127;-->實際是調用Integer.valueOf(i):valueOf的源碼如下:
        public static Integer valueOf(int i) {
            assert IntegerCache.high >= 127;
            if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }

3.3 Character類特殊方法

public static boolean isUpperCase(char ch):確定指定字符是否爲大寫字母; 
public static boolean isLowerCase(char ch):確定指定字符是否爲小寫字母;
public static boolean isDigit(char ch):確定指定字符是否爲數字;
public static char toLowerCase(char ch):使用取自UnicodeData文件的大小寫映射信息將字符參數轉換爲小寫;
public static char toUpperCase(char ch):使用取自UnicodeData文件的大小寫映射信息將字符參數轉換爲大寫.

3.4 代碼案例

public class MyIntegerDemo {
    public static void main(String[] args) {
        /*
         * Integer中有個byte類型(-128~127)的緩衝池.直接使用賦值的方式時,如果數值在byte的取值範圍內,是直接從byte緩衝池中返回該值,不會創建對象;
         * 如果不在byte的緩衝池中,則會通過new Integer(i)的方式創建一個對象並返回.
         * Integer i1 = 127;-->實際是調用Integer.valueOf(i):valueOf的源碼如下:
         * public static Integer valueOf(int i) {
                assert IntegerCache.high >= 127;
                if (i >= IntegerCache.low && i <= IntegerCache.high)
                    return IntegerCache.cache[i + (-IntegerCache.low)];
                return new Integer(i);
            }
         */
        Integer i1 = 127;
        Integer i2 = 127;
        System.out.println(i1==i2); // true
        System.out.println(i1.equals(i2)); // true

        Integer i3 = 128;
        Integer i4 = 128;
        System.out.println(i3==i4); // false
        System.out.println(i3.equals(i4)); // true
    }
}

4. 正則表達式

正則表達式:符合一定規則的表達式(字符串).

4.1 Pattern類

Pattern類:正則表達式的編譯表示形式.

4.2 正則表達式的應用

// 判斷功能:String類的方法
public boolean matches(String regex):告知此字符串是否匹配給定的正則表達式. 
// 分割功能:String類的方法
public String[] split(String regex):根據給定正則表達式的匹配拆分此字符串.按照指定分隔符進行分割字符串,得到的是字符串數組.
// 替換功能:String類的方法
public String replaceAll(String regex,String replacement):使用給定的 replacement 替換此字符串所有匹配給定的正則表達式的子字符串。 
//  獲取功能:Pattern和Matcher配合使用
// 1.將規則編譯成Pattern對象
// 2.通過模式對象獲取匹配器對象
// 3.通過匹配器對象的find方法查找是否有滿足要求的子字符串
// Matcher類的方法:必須先調用find方法,group方法才能調用.
public boolean find(int start):重置此匹配器,然後嘗試查找匹配該模式,從指定索引開始的輸入序列的下一個子序列. 
public String group():返回由以前匹配操作所匹配的輸入子序列.

4.3 案例代碼

public class MyRegexDemo {
    public static void main(String[] args) {
        /*
         * 判斷功能,校驗郵箱
         */
         // 定義郵箱的規則
         String regex = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
         Scanner sc = new Scanner(System.in);
         String email = sc.nextLine();
         boolean flag = email.matches(regex);
         System.out.println(flag);
        /*
         * 分割功能
         */
        String s = "java,hello";
        String[] strings = s.split(",");
        System.out.println(Arrays.toString(strings));
        String s1 = "java.hello";
        String[] strings1 = s1.split("\\."); // .需要使用斜槓進行轉義,java中兩個斜槓代表一個斜槓
        System.out.println(Arrays.toString(strings1));
        String s2 = "java     hello     world";
        String[] strings2 = s2.split(" +"); // 多個空格需要使用+表示多個
        System.out.println(Arrays.toString(strings2));
        // windows中的路徑分割符是單斜槓,需要使用進行轉義
        String s3 = "E:\\develop\\JavaAdvanceWorkSpace\\day06\\src\\com\\itheimamyregex\\MyRegexDemo.java";
        String[] strings3 = s3.split("\\\\"); // Java中要匹配s3中的雙斜槓,Java中斜槓要進行轉義,需要使用4個斜槓表示路徑中的2個斜槓
        System.out.println(Arrays.toString(strings3));
        /*
         * 替換功能,將字符串中指定的字符替換爲指定的字符
         * 如將指定字符串中的數字替換爲*號
         */
        String data = "Somnus0809";
        String regex3 = "\\d";
        String rdata = data.replaceAll(regex3, "*");
        System.out.println("rdata:"+rdata); // rdata:Somnus****
        /*
         * 獲取功能: 獲取字符串中:
         * "wo zai hei ma cheng xu yuan cheng du fen xiao qu xue xi java bian cheng"
         * 有4個字母的字符串
         */
        String ss = "wo zai hei ma cheng xu yuan cheng du fen xiao qu xue xi java bian cheng";
        // 定義規則
        String regex2 = "\\b\\w{4}\\b";
        // 將規則編譯成Pattern對象
        Pattern p = Pattern.compile(regex2);
        // 通過模式對象獲取匹配器對象
        Matcher m = p.matcher(ss);
        // 通過匹配器對象的find方法查找是否有滿足要求的子字符串
        while (m.find()) {
            // group方法調用之前必須先調用find方法
            System.out.println(m.group());
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章