Java學(xué)習(xí)筆記 - 第026天

每日要點

正則表達(dá)式

例子1:零寬正向先行斷言、零寬負(fù)向先行斷言、零寬正向后行斷言、零寬負(fù)向后行斷言

class Test01 {

    public static void main(String[] args) {
        // 零寬正向先行斷言
        String str1 = "a regular expression";
        // 匹配后面是gular的re
        Pattern pattern1 = Pattern.compile("re(?=gular)\\S+");
        Matcher matcher1 = pattern1.matcher(str1);
        while (matcher1.find()) {
            System.out.println(matcher1.group());
        }
        
        matcher1.reset();
        // 零寬負(fù)向先行斷言
        // 匹配后面不是gular的re
        matcher1.usePattern(Pattern.compile("re(?!gular)\\S+"));
        while (matcher1.find()) {
            System.out.println(matcher1.start() + "-" + matcher1.end());
            System.out.println(matcher1.group());
        }
        
        // 零寬正向后行斷言
        String str2 = "regex represents regular expression";
        // 找re前面有其他字符(re不在最開頭)的re
        Pattern pattern2 = Pattern.compile("(?<=\\w)re\\S+");
        Matcher matcher2 = pattern2.matcher(str2);
        while (matcher2.find()) {
            System.out.println(matcher2.start() + "-" + matcher2.end());
            System.out.println(matcher2.group());
        }
        
        matcher2.reset();
        // 零寬負(fù)向后行斷言
        // 找re前面沒有其他字符的re
        matcher2.usePattern(Pattern.compile("(?<!\\w)re\\S+"));
        while (matcher2.find()) {
            System.out.println(matcher2.start() + "-" + matcher2.end());
            System.out.println(matcher2.group());
        }
    }
}

異常

自定義異常

例子1:以前計算器例子
自定義異常

/**
 * 分?jǐn)?shù)操作異常
 * @author Kygo
 *
 */
@SuppressWarnings("serial")
public class FractionException extends RuntimeException {
    
    /**
     * 構(gòu)造器
     * @param message 異常相關(guān)信息
     */
    public FractionException(String message) {
        super(message);
    }
}

計算器類部分:

    /**
     * 構(gòu)造器 : 指定分子和分母創(chuàng)建分?jǐn)?shù)對象
     * @param num 分子
     * @param den 分母
     * @throws RuntimeException 如果分母為0就會引發(fā)異常
     */
    public Fraction(int num, int den) {
        if (den == 0) {
            throw new FractionException("分母不能為0");
        }
        this.num = num;
        this.den = den;
        this.normalize();
        this.simplify();
    }
其他異常和錯誤

例子2:

class Test02 {

    public static int sum(int n) {
        if (n == 1) return 1;
        return n + sum(n - 1);
    }
    
    public static void main(String[] args) {
        String str = "a123";
        // NumberFormatException
        int b = Integer.parseInt(str);
        System.out.println(b);
        
        Scanner scanner = new Scanner(System.in);
        System.out.print("a = ");
        // InputMismatchException
        int a = scanner.nextInt();
        System.out.println(a);
        scanner.close();
        // StackOverflowError
        // System.out.println(sum(100000));
        // OutOfMemoryError
        // List<String> list = new ArrayList<>();
        // while (true) {
            // list.add("hello");
        // }
    }
}
關(guān)機(jī)鉤子

例子3::

@SuppressWarnings("serial")
class Annoyance extends Exception {}

@SuppressWarnings("serial")
class Sneeze extends Annoyance {}

class Test03 {

    public static void main(String[] args) {
        // 獲得JVM
        Runtime rt = Runtime.getRuntime();
        // -Xms32M -Xmx32M
        System.out.println(rt.freeMemory());
        System.out.println(rt.totalMemory());
        // 注冊一個關(guān)機(jī)鉤子(在關(guān)閉JVM時要執(zhí)行的方法)
        rt.addShutdownHook(new Thread(() -> {
            System.out.println("Fuck the world.");
        }));
        
        try {
            try {
                throw new Sneeze();
            } catch (Annoyance a) {
                System.out.println("Caught Annoyance");
                throw a;
            }
        }
        catch (Sneeze e) {
            System.out.println("Caught Sneeze");
        //  return ;
            System.exit(0);
        }
        finally {
            System.out.println("hello");
        }
    }
}
異常接口和繼承相關(guān)例子

構(gòu)造器不會被繼承 子類只能調(diào)用父類構(gòu)造器 如果父類構(gòu)造器聲明了異常
子類構(gòu)造器必須聲明能夠處理該異常的異常的類型

例子4:

@SuppressWarnings("serial")
class Ex1 extends Exception { }
@SuppressWarnings("serial")
class Ex2 extends Ex1 { }
@SuppressWarnings("serial")
class Ex3 extends Exception { }

interface C {
    public void foo() throws Ex1;
}

abstract class A {
    public A() throws Ex2 { }
    public abstract void foo() throws Ex3;
}

class B extends A implements C {
    // 構(gòu)造器不會被繼承 子類只能調(diào)用父類構(gòu)造器 如果父類構(gòu)造器聲明了異常
    // 子類構(gòu)造器必須聲明能夠處理該異常的異常的類型
    public B() throws Ex1 { }
    
    // foo()方法有雙重來源 可以聲明的異常是Ex1和Ex3的交集
    // 由于Ex1和Ex3兩種異常沒有交集 所以此處不能聲明任何受檢異常
    @Override
    public void foo() {
    }
}

class Test04 {
    
    public static void bar(A a) {
        try {
            a.foo();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            bar(new B());
        }
        catch (Exception e) {   // 異常捕獲遵循里氏替換原則
            e.printStackTrace();
        }
    }
錯使用誤異常try-catch的例子

例子5:

class Test05 {

    public static void main(String[] args) {
        int[] array = { 12, 34, 6, 99, 27 };
        int index = 0;
        // 齷齪做法: 用異常處理正常業(yè)務(wù)邏輯
        try {
            while (true) {
                System.out.println(array[index]);
                index += 1;
            } 
        }
        catch (ArrayIndexOutOfBoundsException e) {
        }
    }
}

齷齪做法: 用異常處理正常業(yè)務(wù)邏輯

垃圾回收

例子6:

class Shit {
    // 當(dāng)垃圾回收器回收Shit對象時可能會調(diào)用該方法
    @Override
    protected void finalize() throws Throwable {
        System.out.println("狗屎沒了!!!");
    }
}

class Test06 {

    public static void main(String[] args) {
        // 強(qiáng)引用
        Shit shit = new Shit();
        System.out.println(shit);
        // 軟引用、弱引用和幻引用
        // 請查閱資料明天進(jìn)行講解
//      SoftReference<Shit> sf;
//      WeakReference<Shit> wf;
        shit = null;
        System.gc();
        // Runtime.getRuntime().gc();
    }
}

對容器數(shù)據(jù)的相關(guān)操作

大數(shù)據(jù)處理常用操作:
過濾(filter) -> 映射(map) -> 歸約(reduce)
過濾 - 把無用信息排除掉
映射 - 把數(shù)據(jù)轉(zhuǎn)換成系統(tǒng)需要的格式
歸約 - 把多項數(shù)據(jù)合并成一項數(shù)據(jù)得出結(jié)論性的東西
例子7:

class Test07 {

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("apple");
        list.add("pitaya");
        list.add("orange");
        list.add("grape");
        list.add("watermelon");
        // Java 8 - Lambda表達(dá)式
        list.forEach(elem -> {
            System.out.println(elem);
        });
        // Java 8 - 方法引用(高階函數(shù))
        list.forEach(System.out::println);
        // 大數(shù)據(jù)處理常用操作:
        // 過濾(filter) -> 映射(map) -> 歸約(reduce)
        // 過濾 - 把無用信息排除掉
        // 映射 - 把數(shù)據(jù)轉(zhuǎn)換成系統(tǒng)需要的格式
        // 歸約 - 把多項數(shù)據(jù)合并成一項數(shù)據(jù)得出結(jié)論性的東西
        // Java 8 集合的流式操作
        // - stream() / - parallelStream()
        list.stream()
        .filter(x -> { return x.length() > 5; })
        .map(x -> { return x.toUpperCase(); })
        .forEach(x -> { System.out.println(x); });
        
        String result = list.parallelStream()
        .filter(x -> { return x.length() > 5; })
        .map(x -> { return x.toUpperCase(); })
        .reduce("", (s1, s2) -> { return s1 + s2; });
        System.out.println(result);
    }
}

網(wǎng)絡(luò)編程

例子8:使用百度身份證識別接口,百度APIStore的身份證查詢服務(wù)

// 百度APIStore的身份證查詢服務(wù)
// 通過HTTP協(xié)議請求服務(wù)器提供的JSON格式的數(shù)據(jù)
class Test08 {
    public static void main(String[] args) {
        String string = request("http://apis.baidu.com/apistore/idservice/id", "id=511623199505201158");
        System.out.println(string);
    }

    public static String request(String httpUrl, String httpArg) {
        String result = "";
        StringBuffer sb = new StringBuffer();

        HttpURLConnection connection = null;
        try {
            // 將URL和請求參數(shù)拼接到一起組成完整的URL
            URL url = new URL(httpUrl + "?" + httpArg);
            // 通過URL獲得HTTPURLConnection對象(代表對服務(wù)器的連接)
            connection = (HttpURLConnection) url.openConnection();
            // 設(shè)置請求方法為GET方法
            connection.setRequestMethod("GET");
            // 填入apikey到HTTP請求頭中
            connection.setRequestProperty("apikey", "2fa58657897cc7c76740406af043b75d");
            // 通過連接對象連到服務(wù)器
            connection.connect();
            // 建立輸入流從服務(wù)器獲取數(shù)據(jù)
            try (InputStream is = connection.getInputStream()) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String str = null;
                while ((str = reader.readLine()) != null) {
                    sb.append(str);
                    sb.append("\r\n");
                }
                result = sb.toString();
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 斷開連接
            if (connection != null) {
                connection.disconnect();
            }
        }
        return result;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,406評論 6 538
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,034評論 3 423
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,413評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,449評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 72,165評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,559評論 1 325
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,606評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,781評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,327評論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,084評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,278評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,849評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,495評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,927評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,172評論 1 291
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,010評論 3 396
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 48,241評論 2 375

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