每日要點
正則表達(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;
}
}