java-lang和commons-lang包

java-lang

java.lang包包含著Java最基礎(chǔ)和核心的類,在編譯時會自動導(dǎo)入。它提供了java中基礎(chǔ)類。常用的有Object類、String類、基本類型的包裝類、Math計算類等等。
包的位置:%JAVA_HOME%/jre/lib/rt.jar

包裝類:

每個基本類型在java.lang包中都有一個相應(yīng)的包裝類

基本類型對應(yīng)包裝類.jpg

包裝類.jpg

包裝類的作用:
集合不允許存放基本類型數(shù)據(jù),存放數(shù)字時,要用包裝類型

包裝類的構(gòu)造方法

1.所有包裝類都可以將與之對應(yīng)的基本數(shù)據(jù)類型作為參數(shù),來構(gòu)造他們的實例

如:Integer i = new Integer(1);

2.處character類外,其他包裝類可將一個字符串作為參數(shù)構(gòu)造它們的實例

如:Integer i = new Integer("123");

注意事項:
1.Boolean類構(gòu)造方法參數(shù)為String類型時,若該字符串內(nèi)容為true(不考慮大小寫),則該Boolean對象表示true,否則表示false。(內(nèi)部比較時用的是equalsIgnoreCase)

Boolean boolean1 = new Boolean("TRUE");

2.當(dāng)Number包裝類構(gòu)造方法參數(shù)為String類型時,字符串不能為null,且該字符串必須可以解析為相應(yīng)的基本數(shù)據(jù)類型的數(shù)據(jù),否則編譯通過,運行時NumberFormatException(數(shù)字格式)異常

Integer integer = new Integer("null");

自動拆裝箱:

也解決了集合中不能放基本類型的問題

什么時候自動裝箱:
Integer i =100;
相當(dāng)于編譯器自動為您作以下的語法編譯:Integer i = Integer.valueOf(100);
什么時候自動拆箱:
自動拆箱(unboxing),也就是將對象中的基本數(shù)據(jù)從對象中自動取出
Integer i = 10; //裝箱 
int t = i; //拆箱,實際上執(zhí)行了 int t = i.intValue();
Integer的自動裝箱
//在-128~127 之外的數(shù)
        Integer i1 = 200;
        Integer i2 = 200;
        System.out.println("i1==i2: " + (i1 == i2));
        // 在-128~127 之內(nèi)的數(shù)
        Integer i3 = 100;
        Integer i4 = 100;
        System.out.println("i3==i4: " + (i3 == i4));

輸出的結(jié)果是:

i1==i2: false
i3==i4: true

equals() 比較的是兩個對象的值(內(nèi)容)是否相同。
"==" 比較的是兩個對象的引用(內(nèi)存地址)是否相同,

int的自動裝箱,是系統(tǒng)執(zhí)行了Integer.valueOf(int i),源碼:

  public static Integer valueOf(int i) {
        if(i >= -128 && i <= IntegerCache.high)   //默認是127
            return IntegerCache.cache[i + 128];
        else
            return new Integer(i);
    }

對于–128到127(默認是127)之間的值,Integer.valueOf(int i) 返回的是緩存的Integer對象(并不是新建對象)
所以范例中,i3 與 i4實際上是指向同一個對象。
而其他值,執(zhí)行Integer.valueOf(int i) 返回的是一個新建的 Integer對象,所以范例中,i1與i2 指向的是不同的對象。

Math類

floor: 取整,返回小于目標(biāo)數(shù)的最大整數(shù)
ceil:取整,返回大于目標(biāo)數(shù)的最小整數(shù)
round:四舍五入取整

System.out.println("Math.floor(1.2):" + Math.floor(1.2));//1.0
        System.out.println("Math.ceil(1.2):" + Math.ceil(1.2));//2.0
        System.out.println("Math.round(2.3):" + Math.round(2.3));//2

三角運算(正弦、余弦、正切等)

異常

一種嚴重的:Error,一種不太嚴重的:Exception
對于Error,一般不寫針對性的代碼進行處理
對于不太嚴重的,java對于Exception可以通過針對性的方式進行處理
特殊情況:try對應(yīng)多個catch時,如果有父類的catch語句塊,一定要放在下面。
java.lang.Throwable:
Throwable
| --- Error
| --- Exception
try、catch、finally使用:
try{}用來定義需要被檢測的代碼,catch(){}用來處理異常的代碼,finally{}中是一定會執(zhí)行的代碼
注意:
finally中定義的通常是 關(guān)閉資源代碼。因為資源必須釋放。當(dāng)執(zhí)行到System.exit(0)時,finally不會執(zhí)行。
JDK1.7異常處理新特性:
多個catch用一個catch替代
格式:
catch(異常1|異常2|異常3...變量名)

輸出結(jié)果?

public class Testyc {
    public static void main(String[] args) {
        try {
            int  i = 1/0;
        } catch (Exception e) {
            System.out.println("catch");
            return; 
        }finally{
            System.out.println("finally");
        }
    }
}
catch
finally

catch里面有return語句,finally里面的語句還會執(zhí)行,在return前執(zhí)行。

線程

定義線程

1.繼承java.lang.Thread類
此類重寫Thread類的run()方法。

public class TestxcThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(getName()+":"+i);
        }
    }
}

public class TestThread {
    public static void main(String[] args) {
        TestxcThread xc1 = new TestxcThread();
        TestxcThread xc2 = new TestxcThread();  
        xc1.setName("線程1");
        xc2.setName("線程2");
        xc1.start();
        xc2.start();
    }
}

開啟線程:start(),這個方法其實做了兩件事情,第一,讓線程啟動,第二,自動調(diào)用run()方法
2.實現(xiàn)java.lang.Runnable接口
重寫run()方法

public class TestxcThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(getName()+":"+i);
        }
    }
}

public class TestRunnable {
    public static void main(String[] args) {
        TestxcRunnable test1 = new TestxcRunnable();
        TestxcRunnable test2 = new TestxcRunnable();
        
        Thread xc1 = new Thread(test1);
        Thread xc2 = new Thread(test2);
        
        xc1.setName("線程1");
        xc2.setName("線程2");
        
        xc1.start();
        xc2.start();
    }
}
//start->start0(調(diào)用 run)->target(new Tread 時會把target附上值,會執(zhí)行test1.run();

    public void run() {
    if (target != null) {
        target.run();
      }
    }
線程生命周期
生命周期.png

線程的生命周期,把圖轉(zhuǎn)化為文字就是:
線程通過new方法創(chuàng)建,調(diào)用start()方法,線程進入就緒狀態(tài),等待系統(tǒng)的調(diào)度。當(dāng)系統(tǒng)調(diào)度,進入運行狀態(tài)。正常結(jié)束或者異常退出,進程進入死亡狀態(tài)。
處于運行狀態(tài)的線程yieId()方法,線程轉(zhuǎn)為就緒狀態(tài)。
處于運行狀態(tài)的線程遇到wait()方法,線程處于等待狀態(tài),需要notify()/notifyAll()來喚醒線程,喚醒后的線程處于鎖定狀態(tài),獲取了“同步鎖”之后,線程才轉(zhuǎn)為就緒狀態(tài)。

wait()、notify()、notifyAll()

wait()、notify()、notifyAll()是三個定義在Object類里的方法,可以用來控制線程的狀態(tài)。
這三個方法最終調(diào)用的都是jvm級的native方法。隨著jvm運行平臺的不同可能有些許差異。
如果對象調(diào)用了wait方法就會使持有該對象的線程把該對象的控制權(quán)交出去,然后處于等待狀態(tài)。
如果對象調(diào)用了notify方法就會通知某個正在等待這個對象的控制權(quán)的線程可以繼續(xù)運行。
如果對象調(diào)用了notifyAll方法就會通知所有等待這個對象控制權(quán)的線程繼續(xù)運行。
其中wait方法有三個方法:
wait()
wait(long)
wait(long,int)
wait方法通過參數(shù)可以指定等待的時長。如果沒有指定參數(shù),默認一直等待直到被通知。

wait和sleep的區(qū)別

分析這兩個方法:從執(zhí)行權(quán)和鎖上來分析:
wait:可以指定時間也可以不指定時間。不指定時間,只能由對應(yīng)的notify或者notifyAll來喚醒。
sleep:必須指定時間,時間到自動從凍結(jié)狀態(tài)轉(zhuǎn)成運行狀態(tài)(臨時阻塞狀態(tài))。
wait:線程會釋放執(zhí)行權(quán),而且線程會釋放鎖。
Sleep:線程會釋放執(zhí)行權(quán),但不是不釋放鎖。

commons-lang

Apache Commons lang包提供了標(biāo)準(zhǔn)Java庫函數(shù)里沒有提供的Java核心類的操作方法。Apache Commons Lang為java.lang API提供了大量的輔助工具,尤其是在String操作方法。

StringUtils

如何判斷字符串為空的情況?

String a=null;
if(a!=null && a!=""){}

需要判斷的地方有很多,代碼累贅
StringUtils : 該類主要提供對字符串的操作,對null是安全的,主要提供了字符串查找,替換,分割,去空白,去掉非法字符等等操作

//        1.public static boolean isEmpty(String str)
//        判斷某字符串是否為空,為空的標(biāo)準(zhǔn)是str == null 或 str.length() == 0
//        下面是示例:
        System.out.println(StringUtils.isEmpty(null));// true
        System.out.println(StringUtils.isEmpty(""));// true
        System.out.println(StringUtils.isEmpty(" "));// false
        System.out.println(StringUtils.isEmpty("        "));// false
        System.out.println(StringUtils.isEmpty("bob"));// false
        System.out.println(StringUtils.isEmpty(" bob "));// false
        // 2.public static boolean isNotEmpty(String str)
        //判斷某字符串是否非空,等于!isEmpty(String str)
        //下面是示例:
        System.out.println(StringUtils.isNotEmpty(null));// false
        System.out.println(StringUtils.isNotEmpty(""));// false
        System.out.println(StringUtils.isNotEmpty(" "));// true
        System.out.println(StringUtils.isNotEmpty("         "));// true
        System.out.println(StringUtils.isNotEmpty("bob"));// true
        System.out.println(StringUtils.isNotEmpty(" bob "));// true
        //3. public static boolean isBlank(String str)
        //判斷某字符串是否為空或長度為0或由空白符(whitespace)構(gòu)成
        ///下面是示例:
        StringUtils.isBlank(null);// true
        StringUtils.isBlank("");// true
        StringUtils.isBlank(" ");// true
        StringUtils.isBlank("        ");// true
        System.out.println(StringUtils.isBlank("\t \n \f \r"));// true
        System.out.println(StringUtils.isBlank("\b"));// false
        System.out.println(StringUtils.isBlank(" bob "));// false
        //4. public static boolean isNotBlank(String str)
        //判斷某字符串是否不為空且長度不為0且不由空白符(whitespace)構(gòu)成,
        //等于!isBlank(String str)
        // 下面是示例:
        System.out.println(StringUtils.isNotBlank(null));       // false
        System.out.println(StringUtils.isNotBlank(""));               // false
        System.out.println(StringUtils.isNotBlank(" "));          // false
        System.out.println(StringUtils.isNotBlank("         "));        //false
        System.out.println(StringUtils.isNotBlank("\t \n \f \r"));     // false
        System.out.println(StringUtils.isNotBlank("\b"));              // true
        System.out.println(StringUtils.isNotBlank("bob"));           // true
        System.out.println(StringUtils.isNotBlank(" bob "));   // true
        //5. public static String trim(String str)
        //去掉字符串兩端的控制符(control characters, char <= 32)
        //如果輸入為null則返回null
        //下面是示例:
        System.out.println(StringUtils.trim(null));                // null
        System.out.println(StringUtils.trim(""));                 // ""
        System.out.println(StringUtils.trim(" "));                          // ""
        System.out.println(StringUtils.trim("     \b \t \n \f \r    ")); // ""
        System.out.println(StringUtils.trim("     \n\tss   \b"));       // "ss"
        System.out.println(StringUtils.trim(" d   d dd     "));     // "d   d dd"
        System.out.println(StringUtils.trim("dd     "));            // "dd"
        System.out.println(StringUtils.trim("     dd       "));           // "dd"
        //6.public static String trimToNull(String str)
        //去掉字符串兩端的控制符
        //如果變?yōu)閚ull或"",則返回null
        //下面是示例:
        StringUtils.trimToNull(null);                // null
        StringUtils.trimToNull("");                           // null
        StringUtils.trimToNull(" ");                          // null
        StringUtils.trimToNull("     \b \t \n \f \r    "); // null
        StringUtils.trimToNull("     \n\tss   \b");     // "ss"
        StringUtils.trimToNull(" d   d dd     ");        // "d   d dd"
        StringUtils.trimToNull("dd     ");           // "dd"
        StringUtils.trimToNull("     dd       ");          // "dd"
        System.out.println(StringUtils.contains("defg", "ef"));//檢查一字符串是否包含另一字符串.
        System.out.println(StringUtils.containsOnly("ef", "defg"));//檢查一字符串是否為另一字符串的子集

        System.out.println("去除字符中的空格.");
        System.out.println(StringUtils.deleteWhitespace("aa  bb  cc"));//aabbcc

        System.out.println("分隔符處理成數(shù)組.");
        String[] strArray = StringUtils.split("a,b,,c,d,null,e", ",");
        System.out.println(strArray.length);//6

        System.out.println("縮短到某長度,用...結(jié)尾.");
        System.out.println(StringUtils.abbreviate("The quick brown fox jumps over the lazy dog.", 10));//The qui...
        System.out.println(StringUtils.abbreviate("The quick brown fox jumps over the lazy dog.", 15, 10));//... fox...
ArrayUtils

ArrayUtils 提供了數(shù)組的復(fù)制,查找,獲取子數(shù)組,反轉(zhuǎn)等功

//判斷數(shù)組是否為空(null和length=0的時候都為空)
ArrayUtils.isEmpty(new int[0]);// true
ArrayUtils.isEmpty(new Object[] { null });// false

//合并兩個數(shù)組
ArrayUtils.addAll(new int[] { 1, 3, 5 }, new int[] { 2, 4 });// {1,3,5,2,4}

//刪除數(shù)組中某個位置上的數(shù)據(jù)
        ArrayUtils.remove(new int[] { 1, 3, 5 }, 1);// {1,5}

// 刪除數(shù)組中某個對象(從正序開始搜索,刪除第一個)
ArrayUtils.removeElement(new int[] { 1, 3, 5 }, 3);// {1,5}

//Null處理,如果輸入的兩個數(shù)組都為null時候則返回true
ArrayUtils.isEquals(new int[] { 1, 2, 3 }, null);// false
ArrayUtils.isEquals(null, null);// true

//查詢某個Object是否在數(shù)組中
ArrayUtils.contains(new int[] { 3, 1, 2 }, 1);// true

//輸出數(shù)組中的元素內(nèi)容
ArrayUtils.toString(new int[] { 1, 4, 2, 3 });// {1,4,2,3}
ArrayUtils.toString(new Integer[] { 1, 4, 2, 3 });// {1,4,2,3}
ArrayUtils.toString(null, "I'm nothing!");// I'm nothing!
DateUtils和DateFormatUtils

DateUtils 主要提供了對日期的操作,包括日期加減,日期格式化,日期比較等。它們在org.apache.commons.lang.time包下。

1.與SUN的SimpleDateFormat相比 ,其主要優(yōu)點是:線程安全。
2.對應(yīng)于SimpleDateFormat的format()的方法,是DateFormatUtils 的format系列方法,常用的就是:

 public static String format(Date date, String pattern)

3.對應(yīng)與SimpleDateFormat的parse()的方法,是DateUtils的parseDate方法,即:

public static Date parseDate(String dateValue) throws DateParseException

4.日期舍入與截整,DateUtils的truncate()方法可以將日期按照任意范圍截整,關(guān)鍵看第二個參數(shù)。

public static Date truncate(Date date, int field)

第二個參數(shù)取自Calendar的常量,可以是MONTH、DATE、HOUR等多種;
5.判斷是否是同一天,DateUtils的isSameDay()方法

public static boolean isSameDay(Date date1, Date date2)

6.DateFormatUtils定義了很多內(nèi)置的固定日期格式,均為FastDateFormat類型,比如 ISO_DATE_FORMAT。使用 FastDateFormat的format()方法可以直接將日期格式化為內(nèi)置的固定格式。

public String format(Date date)
        //常用日期格式的格式化操作: 
        //以 yyyy-MM-dd 格式化:
        System.out.println(DateFormatUtils.ISO_DATE_FORMAT.format(new Date()));//2017-06-17
        //以 yyyy-MM-dd'T'HH:mm:ss 格式化:
        System.out.println(DateFormatUtils.ISO_DATETIME_FORMAT.format(new Date()));//2017-06-17T12:51:18
        //以 HH:mm:ss 格式化:
        System.out.println(DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(new Date()));//12:51:18
        
        //自定義日期格式的格式化操作:
        // 以 yyyy-MM-dd HH:mm:ss 格式化Date對象:
        System.out.println(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));//2017-06-17 12:51:18
        //以 yyyy-MM-dd HH:mm:ss 格式化Calendar對象:
        System.out.println(DateFormatUtils.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss"));//2017-06-17 12:51:18
        //以 yyyy-MM-dd HH:mm:ss 格式化TimeInMillis:
        System.out.println(DateFormatUtils.format(Calendar.getInstance().getTimeInMillis(), "yyyy-MM-dd HH:mm:ss"));//2017-06-17 12:51:18
BooleanUtils

BooleanUtils用來操作基礎(chǔ)布爾或者布爾對象,很多方法在工作中可以經(jīng)常使用,下面是該工具類的一個藍圖:


image.png
        Boolean[] arr = new Boolean[]{true,true};
        //一假即假
        BooleanUtils.and(arr);         // true
        System.out.println(BooleanUtils.isTrue(Boolean.TRUE));//true
        System.out.println(BooleanUtils.isTrue(Boolean.FALSE));//false
        System.out.println(BooleanUtils.isTrue(null));//false
        
        System.out.println(BooleanUtils.isNotTrue(Boolean.TRUE));//false
        System.out.println(BooleanUtils.isNotTrue(Boolean.FALSE));//false
        System.out.println(BooleanUtils.isNotTrue(null));//true

Apache Commons只是工具類庫,并不能解決所有的問題,但是可以提高代碼的效率。Commons的工具類還有很多,還是需要大家在工作中不斷慢慢的積累。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,967評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,273評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 175,870評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,742評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 71,527評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,010評論 1 322
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,108評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,250評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,769評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,656評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,853評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,371評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,103評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,472評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,717評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,487評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 47,815評論 2 372

推薦閱讀更多精彩內(nèi)容