user3 = dao.list();
+ System.out.println(user3);
+ }
}
diff --git a/src/main/java/Advances/IOFlow/demo1.java b/src/main/java/Advances/IOFlow/demo1.java
index e208283f..0bdfc3a7 100644
--- a/src/main/java/Advances/IOFlow/demo1.java
+++ b/src/main/java/Advances/IOFlow/demo1.java
@@ -3,12 +3,10 @@
// https://www.youtube.com/watch?v=kqG8IQNMN_s&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=584
// https://www.youtube.com/watch?v=lms-HDCYCvQ&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=586
-import org.junit.jupiter.api.Test;
-
import java.io.File;
-import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
+import org.junit.jupiter.api.Test;
/**
* - FileReader demo
diff --git a/src/main/java/Advances/IOFlow/demo2.java b/src/main/java/Advances/IOFlow/demo2.java
index 8dc18f21..04ea7046 100644
--- a/src/main/java/Advances/IOFlow/demo2.java
+++ b/src/main/java/Advances/IOFlow/demo2.java
@@ -6,49 +6,45 @@
import org.junit.jupiter.api.Test;
/** FileWriter demo */
-
public class demo2 {
- /** FileWriter demo 1
- *
- * 1) write in-memory data to file in disk
- *
- * 2) if outfile not existed,
- * -> FileWriter will make a new one automatically
- * if outfile existed,
- * -> FileWriter will overwrite current content (new FileWriter(file, false);)
- * -> FileWriter will append new data to current content (new FileWriter(file, true);)
- *
- */
- @Test
- public void test1() throws IOException {
-
- FileWriter fw = null;
-
+ /**
+ * FileWriter demo 1
+ *
+ * 1) write in-memory data to file in disk
+ *
+ *
2) if outfile not existed, -> FileWriter will make a new one automatically if outfile
+ * existed, -> FileWriter will overwrite current content (new FileWriter(file, false);) ->
+ * FileWriter will append new data to current content (new FileWriter(file, true);)
+ */
+ @Test
+ public void test1() throws IOException {
+
+ FileWriter fw = null;
+
+ try {
+ // step 1) offer file class object, declare plan-to-write file
+ File file = new File("src/main/java/Advances/IOFlow/hello2.txt");
+
+ // step 2) offer FileWriter object, for data writing
+ // FileWriter fw = new FileWriter(file, true); // append to current file (NOT overwrite)
+ fw = new FileWriter(file, false); // NOT append to current file (overwrite)
+
+ // step 3) writing op
+ fw.write(">>> start >>> \n");
+ fw.write("this is Advances.IOFlow.FileWriter output!!!\n");
+ fw.write(">>> end >>> ");
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ if (fw != null) {
try {
- // step 1) offer file class object, declare plan-to-write file
- File file = new File("src/main/java/Advances/IOFlow/hello2.txt");
-
- // step 2) offer FileWriter object, for data writing
- //FileWriter fw = new FileWriter(file, true); // append to current file (NOT overwrite)
- fw = new FileWriter(file, false); // NOT append to current file (overwrite)
-
- // step 3) writing op
- fw.write(">>> start >>> \n");
- fw.write("this is Advances.IOFlow.FileWriter output!!!\n");
- fw.write(">>> end >>> ");
-
+ // step 4) I/O flow close (close FileWriter)
+ fw.close();
} catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (fw != null){
- try{
- // step 4) I/O flow close (close FileWriter)
- fw.close();
- }catch (IOException e){
- e.printStackTrace();
- }
- }
+ e.printStackTrace();
}
+ }
}
+ }
}
-
diff --git a/src/main/java/Advances/IOFlow/demo3.java b/src/main/java/Advances/IOFlow/demo3.java
index 7878cad4..9da3eacd 100644
--- a/src/main/java/Advances/IOFlow/demo3.java
+++ b/src/main/java/Advances/IOFlow/demo3.java
@@ -6,54 +6,53 @@
import org.junit.jupiter.api.Test;
/** FileReader & FileWriter (txt file IO) demo */
-
public class demo3 {
- @Test
- public void test1() throws IOException {
+ @Test
+ public void test1() throws IOException {
- FileReader fr = null;
- FileWriter fw = null;
+ FileReader fr = null;
+ FileWriter fw = null;
- try {
+ try {
+
+ // step 1) create file instance, define read-in and write-out file
+ File srcFile = new File("src/main/java/Advances/IOFlow/hello.txt");
+ File destFile = new File("src/main/java/Advances/IOFlow/hello3.txt");
+
+ // step 2) create input flow, and output flow instance
+ fr = new FileReader(srcFile);
+ fw = new FileWriter(destFile);
- // step 1) create file instance, define read-in and write-out file
- File srcFile = new File("src/main/java/Advances/IOFlow/hello.txt");
- File destFile = new File("src/main/java/Advances/IOFlow/hello3.txt");
+ // step 3) data read-in and write out op
+ char[] cbuf = new char[5];
+ int len; // record read-in char number (to cbuf) every time
+ while ((len = fr.read(cbuf)) != -1) {
+ // NOTE !!! write len char each time
+ fw.write(cbuf, 0, len);
+ }
- // step 2) create input flow, and output flow instance
- fr = new FileReader(srcFile);
- fw = new FileWriter(destFile);
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
- // step 3) data read-in and write out op
- char[] cbuf = new char[5];
- int len; // record read-in char number (to cbuf) every time
- while ((len = fr.read(cbuf))!= -1){
- // NOTE !!! write len char each time
- fw.write(cbuf, 0, len);
- }
+ // step 4) close down IO flow resources
+ // close fr
+ if (fr != null) {
+ try {
+ fr.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ // close fw
+ if (fw != null) {
+ try {
+ fw.close();
} catch (IOException e) {
- e.printStackTrace();
- } finally {
-
- // step 4) close down IO flow resources
-
- // close fr
- if (fr != null){
- try{
- fr.close();
- }catch (IOException e){
- e.printStackTrace();
- }
- }
- // close fw
- if (fw != null){
- try{
- fw.close();
- }catch (IOException e){
- e.printStackTrace();
- }
- }
+ e.printStackTrace();
}
+ }
}
+ }
}
diff --git a/src/main/java/Advances/IOFlow/demo4.java b/src/main/java/Advances/IOFlow/demo4.java
index 5377c74e..212bc223 100644
--- a/src/main/java/Advances/IOFlow/demo4.java
+++ b/src/main/java/Advances/IOFlow/demo4.java
@@ -8,60 +8,59 @@
import org.junit.jupiter.api.Test;
/** FileInputStream & FileOutputStream : (binary file IO) demo */
-
public class demo4 {
- @Test
- public void test1() throws IOException {
+ @Test
+ public void test1() throws IOException {
- // NOTE : we use 字節流 (inputStream, outputStream) for binary file IO
- FileInputStream fis = null;
- FileOutputStream fos = null;
+ // NOTE : we use 字節流 (inputStream, outputStream) for binary file IO
+ FileInputStream fis = null;
+ FileOutputStream fos = null;
- try {
+ try {
- // step 1) create file instance, define read-in and write-out file
- File srcFile = new File("src/main/java/Advances/IOFlow/java.png");
- File destFile = new File("src/main/java/Advances/IOFlow/java2.png");
+ // step 1) create file instance, define read-in and write-out file
+ File srcFile = new File("src/main/java/Advances/IOFlow/java.png");
+ File destFile = new File("src/main/java/Advances/IOFlow/java2.png");
- // step 2) create input flow, and output flow instance
- // NOTE !! we CAN'T use 字符流 (FileReader, FileWriter) for binary file IO (e.g. picture, video)
- // -> we should use 字節流 (inputStream, outputStream) instead
- fis = new FileInputStream(srcFile);
- fos = new FileOutputStream(destFile);
+ // step 2) create input flow, and output flow instance
+ // NOTE !! we CAN'T use 字符流 (FileReader, FileWriter) for binary file IO (e.g. picture, video)
+ // -> we should use 字節流 (inputStream, outputStream) instead
+ fis = new FileInputStream(srcFile);
+ fos = new FileOutputStream(destFile);
- // step 3) data read-in and write out op
- // NOTE !! we use byte for binary file IO here
- byte[] buffer = new byte[5];
- int len; // record read-in char number (to cbuf) every time
- while ((len = fis.read(buffer))!= -1){
- // NOTE !!! write len char each time
- String str = new String(buffer, 0, len);
- System.out.println(str);
- fos.write(buffer, 0, len);
- }
+ // step 3) data read-in and write out op
+ // NOTE !! we use byte for binary file IO here
+ byte[] buffer = new byte[5];
+ int len; // record read-in char number (to cbuf) every time
+ while ((len = fis.read(buffer)) != -1) {
+ // NOTE !!! write len char each time
+ String str = new String(buffer, 0, len);
+ System.out.println(str);
+ fos.write(buffer, 0, len);
+ }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
- // step 4) close down IO flow resources
+ // step 4) close down IO flow resources
- // close fis
- if (fis != null){
- try{
- fis.close();
- }catch (IOException e){
- e.printStackTrace();
- }
- }
- // close fos
- if (fos != null){
- try{
- fos.close();
- }catch (IOException e){
- e.printStackTrace();
- }
- }
+ // close fis
+ if (fis != null) {
+ try {
+ fis.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ // close fos
+ if (fos != null) {
+ try {
+ fos.close();
+ } catch (IOException e) {
+ e.printStackTrace();
}
+ }
}
+ }
}
diff --git a/src/main/java/Advances/IOFlow/demo5.java b/src/main/java/Advances/IOFlow/demo5.java
index 4907c0d5..36151014 100644
--- a/src/main/java/Advances/IOFlow/demo5.java
+++ b/src/main/java/Advances/IOFlow/demo5.java
@@ -2,9 +2,8 @@
// https://www.youtube.com/watch?v=OsfY3Y5ZDGM&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=592
-import org.junit.jupiter.api.Test;
-
import java.io.*;
+import org.junit.jupiter.api.Test;
/** copyFile method demo (FileInputStream, FileOutputStream) demo */
public class demo5 {
diff --git a/src/main/java/Advances/IOFlow/demo6.java b/src/main/java/Advances/IOFlow/demo6.java
index 9b0195af..378b1238 100644
--- a/src/main/java/Advances/IOFlow/demo6.java
+++ b/src/main/java/Advances/IOFlow/demo6.java
@@ -6,122 +6,120 @@
import java.io.*;
import org.junit.jupiter.api.Test;
-/** Buffered IO flow demo1
+/**
+ * Buffered IO flow demo1
*
- * 1) Buffered IO flow : for RAISING file IO efficiency
- * -> why ? java offers "buffer space" internally
- * -> so each time java will load batch of data into "buffer space", then other file io flow can start from there -> better efficiency
+ *
1) Buffered IO flow : for RAISING file IO efficiency -> why ? java offers "buffer space"
+ * internally -> so each time java will load batch of data into "buffer space", then other file io
+ * flow can start from there -> better efficiency
*
- * 2) Buffered IO flow:
- * - BufferedInputStream
- * - BufferedOutputStream
- * - BufferedReader
- * - BufferedFileWriter
+ *
2) Buffered IO flow: - BufferedInputStream - BufferedOutputStream - BufferedReader -
+ * BufferedFileWriter
*
- * 3) "operation flow" (e.g. BufferedReader, BufferedFileWriter) is based on existing flow (e.g. BufferedInputStream, BufferedOutputStream)
+ *
3) "operation flow" (e.g. BufferedReader, BufferedFileWriter) is based on existing flow (e.g.
+ * BufferedInputStream, BufferedOutputStream)
*
- * 4) Summary:
+ *
4) Summary:
*
- * abstract class | 節點流 | 緩衝流
- * InputStream | FileInputStream (read(byte[] buffer)) | BufferedInputStream (read(byte[] buffer))
- * OutputStream | FileOutputStream (write(byte[] buffer, 0, len) | BufferedOutputStream (write(byte[] buffer, 0, len)
- * Reader | FileReader (read(char[] cbuf)) | BufferedReader (read(char[] cbuf))
- * Writer | FileWriter (write(char[] cbuf, 0, len) | BufferedFileWriter (write(char[] cbuf, 0, len)
+ *
abstract class | 節點流 | 緩衝流 InputStream | FileInputStream (read(byte[] buffer)) |
+ * BufferedInputStream (read(byte[] buffer)) OutputStream | FileOutputStream (write(byte[] buffer,
+ * 0, len) | BufferedOutputStream (write(byte[] buffer, 0, len) Reader | FileReader (read(char[]
+ * cbuf)) | BufferedReader (read(char[] cbuf)) Writer | FileWriter (write(char[] cbuf, 0, len) |
+ * BufferedFileWriter (write(char[] cbuf, 0, len)
*/
-
-
public class demo6 {
- /** file IO with non-txt file */
- @Test
- public void test1() throws IOException {
-
- BufferedInputStream bis = null;
- BufferedOutputStream bos = null;
-
- try{
- // step 1) init File
- File srcFile = new File("src/main/java/Advances/IOFlow/java.png");
- File destFile = new File("src/main/java/Advances/IOFlow/java4.png");
-
- // step 2) init flow
- // -> step 2.1) init 節點流 (FileInputStream, FileOutputStream)
- FileInputStream fis = new FileInputStream(srcFile);
- FileOutputStream fos = new FileOutputStream(destFile);
-
- // -> step 2.2) init BufferedInputStream, BufferedOutputStream
- bis = new BufferedInputStream(fis);
- bos = new BufferedOutputStream(fos);
-
- // step 3) copy op, readIn, writeOut
- byte[] buffer = new byte[10];
- int len;
- while ((len = bis.read(buffer)) != -1){
- bos.write(buffer, 0, len);
- /** NOTE !!! we can refresh buffered space explicitly (via below code) */
- //bos.flush();
- }
- }catch (IOException e){
- e.printStackTrace();
- }finally {
-
- // step 4) resources closing
- // -> closing ordering : outer (layer) first, then inner (layer)
- if (bis != null){
- bis.close();
- }
-
- if (bos != null){
- bos.close();
- }
-
- // after outer (layer) (e.g. bis, bos) are closed, java will close inner (layer) (e.g. fos, fis) automatically
- //fos.close();
- //fis.close();
- }
- }
-
- @Test
- public void copyFileWithBufferedTest1() throws IOException {
- String src_file = "src/main/java/Advances/IOFlow/java.png";
- String dest_file = "src/main/java/Advances/IOFlow/java5.png";
-
- copyFileWithBuffered(src_file, dest_file);
+ /** file IO with non-txt file */
+ @Test
+ public void test1() throws IOException {
+
+ BufferedInputStream bis = null;
+ BufferedOutputStream bos = null;
+
+ try {
+ // step 1) init File
+ File srcFile = new File("src/main/java/Advances/IOFlow/java.png");
+ File destFile = new File("src/main/java/Advances/IOFlow/java4.png");
+
+ // step 2) init flow
+ // -> step 2.1) init 節點流 (FileInputStream, FileOutputStream)
+ FileInputStream fis = new FileInputStream(srcFile);
+ FileOutputStream fos = new FileOutputStream(destFile);
+
+ // -> step 2.2) init BufferedInputStream, BufferedOutputStream
+ bis = new BufferedInputStream(fis);
+ bos = new BufferedOutputStream(fos);
+
+ // step 3) copy op, readIn, writeOut
+ byte[] buffer = new byte[10];
+ int len;
+ while ((len = bis.read(buffer)) != -1) {
+ bos.write(buffer, 0, len);
+ /** NOTE !!! we can refresh buffered space explicitly (via below code) */
+ // bos.flush();
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+
+ // step 4) resources closing
+ // -> closing ordering : outer (layer) first, then inner (layer)
+ if (bis != null) {
+ bis.close();
+ }
+
+ if (bos != null) {
+ bos.close();
+ }
+
+ // after outer (layer) (e.g. bis, bos) are closed, java will close inner (layer) (e.g. fos,
+ // fis) automatically
+ // fos.close();
+ // fis.close();
}
-
- /** method : copy file from src to dest via Buffered IO flow */
- public void copyFileWithBuffered(String srcPath, String destPath) throws IOException {
-
- BufferedInputStream bis = null;
- BufferedOutputStream bos = null;
-
- try{
- File srcFile = new File(srcPath);
- File destFile = new File(destPath);
-
- FileInputStream fis = new FileInputStream(srcFile);
- FileOutputStream fos = new FileOutputStream(destFile);
-
- bis = new BufferedInputStream(fis);
- bos = new BufferedOutputStream(fos);
-
- byte[] buffer = new byte[10];
- int len;
- while ((len = bis.read(buffer)) != -1){
- bos.write(buffer, 0, len);
- /** NOTE !!! we can refresh buffered space explicitly (via below code) */
- //bos.flush();
- }
- }catch (IOException e){
- e.printStackTrace();
- }finally {
-
- if (bis != null){
- bis.close();
- }
-
- if (bos != null){
- bos.close();
- }
- }
+ }
+
+ @Test
+ public void copyFileWithBufferedTest1() throws IOException {
+ String src_file = "src/main/java/Advances/IOFlow/java.png";
+ String dest_file = "src/main/java/Advances/IOFlow/java5.png";
+
+ copyFileWithBuffered(src_file, dest_file);
+ }
+
+ /** method : copy file from src to dest via Buffered IO flow */
+ public void copyFileWithBuffered(String srcPath, String destPath) throws IOException {
+
+ BufferedInputStream bis = null;
+ BufferedOutputStream bos = null;
+
+ try {
+ File srcFile = new File(srcPath);
+ File destFile = new File(destPath);
+
+ FileInputStream fis = new FileInputStream(srcFile);
+ FileOutputStream fos = new FileOutputStream(destFile);
+
+ bis = new BufferedInputStream(fis);
+ bos = new BufferedOutputStream(fos);
+
+ byte[] buffer = new byte[10];
+ int len;
+ while ((len = bis.read(buffer)) != -1) {
+ bos.write(buffer, 0, len);
+ /** NOTE !!! we can refresh buffered space explicitly (via below code) */
+ // bos.flush();
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+
+ if (bis != null) {
+ bis.close();
+ }
+
+ if (bos != null) {
+ bos.close();
+ }
}
+ }
}
diff --git a/src/main/java/Advances/IOFlow/demo7.java b/src/main/java/Advances/IOFlow/demo7.java
index 8cd4e0c0..d7fdc0a7 100644
--- a/src/main/java/Advances/IOFlow/demo7.java
+++ b/src/main/java/Advances/IOFlow/demo7.java
@@ -6,57 +6,56 @@
import org.junit.jupiter.api.Test;
/** BufferedReader, BufferedFileWriter demo */
-
public class demo7 {
- /** demo : do txt file copy via BufferedReader, BufferedFileWriter */
- @Test
- public void test1() {
- BufferedReader br = null;
- BufferedWriter bw = null;
- try{
- // step 1) init IO flow
- br = new BufferedReader(new FileReader(new File("src/main/java/Advances/IOFlow/hello.txt")));
- bw = new BufferedWriter(new FileWriter(new File("src/main/java/Advances/IOFlow/hello5.txt")));
-
- // step 2) IO op
-
- // METHOD 1) : use char[] array
-// char[] cbuf = new char[1024];
-// int len;
-// while ((len = br.read(cbuf)) != -1){
-// bw.write(cbuf, 0, len);
-// //bw.flush(); // refresh cache (buffered space), not necessary
-
- // METHOD 2) : use string
- String data;
- while ((data = br.readLine()) != null){
- bw.write(data + "\n"); // NOTE : "\n" is not covered by data by default
- // below code is OK as well
- //bw.write(data);
- //bw.newLine();
- }
-
- }catch (IOException e){
- e.printStackTrace();
- } finally {
-
- // step 3) close resources
- if (bw != null){
- try{
- bw.close();
- }catch (IOException e){
- e.printStackTrace();
- }
- }
-
- if (br != null){
- try{
- br.close();
- }catch (IOException e){
- e.printStackTrace();
- }
- }
+ /** demo : do txt file copy via BufferedReader, BufferedFileWriter */
+ @Test
+ public void test1() {
+ BufferedReader br = null;
+ BufferedWriter bw = null;
+ try {
+ // step 1) init IO flow
+ br = new BufferedReader(new FileReader(new File("src/main/java/Advances/IOFlow/hello.txt")));
+ bw = new BufferedWriter(new FileWriter(new File("src/main/java/Advances/IOFlow/hello5.txt")));
+
+ // step 2) IO op
+
+ // METHOD 1) : use char[] array
+ // char[] cbuf = new char[1024];
+ // int len;
+ // while ((len = br.read(cbuf)) != -1){
+ // bw.write(cbuf, 0, len);
+ // //bw.flush(); // refresh cache (buffered space), not necessary
+
+ // METHOD 2) : use string
+ String data;
+ while ((data = br.readLine()) != null) {
+ bw.write(data + "\n"); // NOTE : "\n" is not covered by data by default
+ // below code is OK as well
+ // bw.write(data);
+ // bw.newLine();
+ }
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+
+ // step 3) close resources
+ if (bw != null) {
+ try {
+ bw.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ if (br != null) {
+ try {
+ br.close();
+ } catch (IOException e) {
+ e.printStackTrace();
}
+ }
}
+ }
}
diff --git a/src/main/java/Advances/IOFlow/demo8.java b/src/main/java/Advances/IOFlow/demo8.java
index e7df8155..ac14d379 100644
--- a/src/main/java/Advances/IOFlow/demo8.java
+++ b/src/main/java/Advances/IOFlow/demo8.java
@@ -2,9 +2,8 @@
// https://www.youtube.com/watch?v=bksGRkSwEBM&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=596
-import org.junit.jupiter.api.Test;
-
import java.io.*;
+import org.junit.jupiter.api.Test;
/** File encrypt/decrypt demo */
public class demo8 {
diff --git a/src/main/java/Advances/IOFlow2/demo1.java b/src/main/java/Advances/IOFlow2/demo1.java
index 6567a986..be50271f 100644
--- a/src/main/java/Advances/IOFlow2/demo1.java
+++ b/src/main/java/Advances/IOFlow2/demo1.java
@@ -4,78 +4,77 @@
// https://www.youtube.com/watch?v=JE-Vpvvdzr0&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=600
import java.io.*;
+import java.nio.charset.StandardCharsets;
+
import org.junit.jupiter.api.Test;
/**
- * IOFlow2 demo1 : Transformation flow :
- * -> transform between 字節流 (byte, 8 bits) & 字符流 (char, 16 bits)
+ * IOFlow2 demo1 : Transformation flow : -> transform between 字節流 (byte, 8 bits) & 字符流 (char, 16
+ * bits)
*
- * 1) Types: (belongs to 字符流 (char, 16 bits))
- * InputStreamReader : byte input to char input
- * OutputStreamWriter : char output to byte output
+ *
1) Types: (belongs to 字符流 (char, 16 bits)) InputStreamReader : byte input to char input
+ * OutputStreamWriter : char output to byte output
*
- * 2) use cases : byte <-> char
+ *
2) use cases : byte <-> char
*
- * 3) decode : byte, byte array -> char, char array
- * encode : char, char array -> byte, byte array
+ *
3) decode : byte, byte array -> char, char array encode : char, char array -> byte, byte array
*/
-
public class demo1 {
- /**
- * demo 1:
- *
- * 1) Exception handling : we should still use try-catch-finally as standard style
- * 2) demo how to use InputStreamReader : byte input -> char input transformation
- */
- @Test
- public void test1() throws IOException {
+ /**
+ * demo 1:
+ *
+ *
1) Exception handling : we should still use try-catch-finally as standard style 2) demo how
+ * to use InputStreamReader : byte input -> char input transformation
+ */
+ @Test
+ public void test1() throws IOException {
- FileInputStream fis = new FileInputStream("src/main/java/Advances/IOFlow2/hello.txt");
- InputStreamReader isr = new InputStreamReader(fis); // use system default char setting
- //InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); // use UTF-8 char type explicitly
+ FileInputStream fis = new FileInputStream("src/main/java/Advances/IOFlow2/hello.txt");
+ InputStreamReader isr = new InputStreamReader(fis); // use system default char setting
+ // InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); // use UTF-8 char type
+ // explicitly
- char[] cbuf = new char[20];
- int len;
- while((len = isr.read(cbuf)) != -1){
- String str = new String(cbuf, 0, len);
- System.out.println(str);
- }
- // close resources
- isr.close();
- fis.close();
+ char[] cbuf = new char[20];
+ int len;
+ while ((len = isr.read(cbuf)) != -1) {
+ String str = new String(cbuf, 0, len);
+ System.out.println(str);
}
+ // close resources
+ isr.close();
+ fis.close();
+ }
- /**
- * demo 2 : InputStreamReader and OutputStreamWriter
- *
- * 1) Exception handling : we should still use try-catch-finally as standard style
- *
- */
- @Test
- public void test2() throws IOException {
+ /**
+ * demo 2 : InputStreamReader and OutputStreamWriter
+ *
+ *
1) Exception handling : we should still use try-catch-finally as standard style
+ */
+ @Test
+ public void test2() throws IOException {
- // step 1) make doc, flow
- File file1 = new File("src/main/java/Advances/IOFlow2/hello.txt");
- File file2 = new File("src/main/java/Advances/IOFlow2/hello2.txt");
+ // step 1) make doc, flow
+ File file1 = new File("src/main/java/Advances/IOFlow2/hello.txt");
+ File file2 = new File("src/main/java/Advances/IOFlow2/hello2.txt");
- FileInputStream fis = new FileInputStream(file1);
- FileOutputStream fos = new FileOutputStream(file2);
+ FileInputStream fis = new FileInputStream(file1);
+ FileOutputStream fos = new FileOutputStream(file2);
- InputStreamReader isr = new InputStreamReader(fis, "utf-8");
- OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");
+ InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
+ OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");
- // step 2) read, write data
- char[] cbuf = new char[20];
- int len;
- while ((len = isr.read(cbuf)) != -1){
- osw.write(cbuf, 0, len);
- }
-
- // step 3) close resources
- isr.close();
- osw.close();
- fis.close();
- fos.close();
+ // step 2) read, write data
+ char[] cbuf = new char[20];
+ int len;
+ while ((len = isr.read(cbuf)) != -1) {
+ osw.write(cbuf, 0, len);
}
+
+ // step 3) close resources
+ isr.close();
+ osw.close();
+ fis.close();
+ fos.close();
+ }
}
diff --git a/src/main/java/Advances/IOFlow3/demo1.java b/src/main/java/Advances/IOFlow3/demo1.java
index 5e357731..f999c7ee 100644
--- a/src/main/java/Advances/IOFlow3/demo1.java
+++ b/src/main/java/Advances/IOFlow3/demo1.java
@@ -3,103 +3,93 @@
// https://www.youtube.com/watch?v=B86dDjwNroY&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=602
/**
- * IOFlow3 demo 1: standard input and output stream
- *
- * 1) System.in, System.out (輸入流, 輸出流)
- * - InputStream, OutputStream
- * 2) PrintStream (打印流)
- * 3) data flow
+ * IOFlow3 demo 1: standard input and output stream
*
+ *
1) System.in, System.out (輸入流, 輸出流) - InputStream, OutputStream 2) PrintStream (打印流) 3) data
+ * flow
*/
-
-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class demo1 {
- /**
- * demo 1: System.in, System.out
- * 1)
- * System.in : input via keyboard
- * System.out : output via terminal
- *
- * 2) we can use System.setIn(InputStream is), System.setOut(OutputStream os)
- * to modify input, output stream
- *
- * 3) (below example) :
- * write a program that will transform input to upper case (if alphabet),
- * quit the program if receive "e" or "exit"
- *
- *
- */
+ /**
+ * demo 1: System.in, System.out 1) System.in : input via keyboard System.out : output via
+ * terminal
+ *
+ *
2) we can use System.setIn(InputStream is), System.setOut(OutputStream os) to modify input,
+ * output stream
+ *
+ *
3) (below example) : write a program that will transform input to upper case (if alphabet),
+ * quit the program if receive "e" or "exit"
+ */
- // intellJ doesn't support unit test input flow, so here we use main method instead
- public static void main(String[] args) {
- InputStreamReader isr = null;
- BufferedReader br = null;
- try{
- isr = new InputStreamReader(System.in);
- br = new BufferedReader(isr);
+ // intellJ doesn't support unit test input flow, so here we use main method instead
+ public static void main(String[] args) {
+ InputStreamReader isr = null;
+ BufferedReader br = null;
+ try {
+ isr = new InputStreamReader(System.in);
+ br = new BufferedReader(isr);
- while (true){
- System.out.println("plz input string");
- String data = br.readLine();
- if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)){
- //System.exit(0);
- System.out.println("program end");
- break;
- }
- String upperCase = data.toUpperCase();
- System.out.println(upperCase);
- }
- }catch (Exception e){
- e.printStackTrace();
- }finally {
- // close resources
- if (br != null){
- try{
- br.close();
- }catch (IOException e){
- e.printStackTrace();
- }
- }
+ while (true) {
+ System.out.println("plz input string");
+ String data = br.readLine();
+ if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {
+ // System.exit(0);
+ System.out.println("program end");
+ break;
+ }
+ String upperCase = data.toUpperCase();
+ System.out.println(upperCase);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ // close resources
+ if (br != null) {
+ try {
+ br.close();
+ } catch (IOException e) {
+ e.printStackTrace();
}
+ }
}
+ }
-// @Test
-// public void test1(){
-//
-// InputStreamReader isr = null;
-// BufferedReader br = null;
-// try{
-// isr = new InputStreamReader(System.in);
-// br = new BufferedReader(isr);
-//
-// while (true){
-// System.out.println("plz input string");
-// String data = br.readLine();
-// if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)){
-// //System.exit(0);
-// System.out.println("program end");
-// break;
-// }
-// String upperCase = data.toUpperCase();
-// System.out.println(upperCase);
-// }
-// }catch (Exception e){
-// e.printStackTrace();
-// }finally {
-// // close resources
-// if (br != null){
-// try{
-// br.close();
-// }catch (IOException e){
-// e.printStackTrace();
-// }
-// }
-// }
-// }
+ // @Test
+ // public void test1(){
+ //
+ // InputStreamReader isr = null;
+ // BufferedReader br = null;
+ // try{
+ // isr = new InputStreamReader(System.in);
+ // br = new BufferedReader(isr);
+ //
+ // while (true){
+ // System.out.println("plz input string");
+ // String data = br.readLine();
+ // if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)){
+ // //System.exit(0);
+ // System.out.println("program end");
+ // break;
+ // }
+ // String upperCase = data.toUpperCase();
+ // System.out.println(upperCase);
+ // }
+ // }catch (Exception e){
+ // e.printStackTrace();
+ // }finally {
+ // // close resources
+ // if (br != null){
+ // try{
+ // br.close();
+ // }catch (IOException e){
+ // e.printStackTrace();
+ // }
+ // }
+ // }
+ // }
}
diff --git a/src/main/java/Advances/IOFlow3/demo2.java b/src/main/java/Advances/IOFlow3/demo2.java
index ffc27e4e..086df88d 100644
--- a/src/main/java/Advances/IOFlow3/demo2.java
+++ b/src/main/java/Advances/IOFlow3/demo2.java
@@ -6,58 +6,52 @@
import org.junit.jupiter.api.Test;
/**
- * IOFlow3 demo 2: DataInputStream, DataOutputStream
+ * IOFlow3 demo 2: DataInputStream, DataOutputStream
*
- * 1) use cases :
- * -> for easily deal with "basic data structure", and "String" in Java
- * -> read/write basic data type, String data type
+ *
1) use cases : -> for easily deal with "basic data structure", and "String" in Java ->
+ * read/write basic data type, String data type
*
- * 2) DataInputStream common methods:
- * readBoolean()
- * readChar()
- * readByte()
- * readFloat()
- * ....
- *
- * 3) DataOutputStream common methods:
+ *
2) DataInputStream common methods: readBoolean() readChar() readByte() readFloat() ....
*
+ *
3) DataOutputStream common methods:
*/
-
public class demo2 {
- /** demo 1 : write file via DataOutputStream */
- @Test
- public void test1() throws IOException {
-
- DataOutputStream dos = new DataOutputStream(new FileOutputStream("src/main/java/Advances/IOFlow3/data.txt"));
- dos.writeUTF("ann");
- dos.flush(); // flush, so every write op will be reflected to output file
- dos.writeInt(17);
- dos.flush();
- dos.writeBoolean(false);
- dos.flush();
-
- // close resource
- dos.close();
- }
-
- /** demo 2 : read file via DataInputStream
- *
- * 1) read basic data type in disk via DataInputStream
- * 2) read data type (code) should be same as data type in disk
- */
- @Test
- public void test2() throws IOException {
-
- DataInputStream dis = new DataInputStream(new FileInputStream("src/main/java/Advances/IOFlow3/data.txt"));
-
- String name = dis.readUTF();
- int age = dis.readInt();
- boolean isMale = dis.readBoolean();
-
- System.out.println("name = " + name + " age = " + age + " isMale = " + isMale);
-
- dis.close();
- }
-
+ /** demo 1 : write file via DataOutputStream */
+ @Test
+ public void test1() throws IOException {
+
+ DataOutputStream dos =
+ new DataOutputStream(new FileOutputStream("src/main/java/Advances/IOFlow3/data.txt"));
+ dos.writeUTF("ann");
+ dos.flush(); // flush, so every write op will be reflected to output file
+ dos.writeInt(17);
+ dos.flush();
+ dos.writeBoolean(false);
+ dos.flush();
+
+ // close resource
+ dos.close();
+ }
+
+ /**
+ * demo 2 : read file via DataInputStream
+ *
+ *
1) read basic data type in disk via DataInputStream 2) read data type (code) should be same
+ * as data type in disk
+ */
+ @Test
+ public void test2() throws IOException {
+
+ DataInputStream dis =
+ new DataInputStream(new FileInputStream("src/main/java/Advances/IOFlow3/data.txt"));
+
+ String name = dis.readUTF();
+ int age = dis.readInt();
+ boolean isMale = dis.readBoolean();
+
+ System.out.println("name = " + name + " age = " + age + " isMale = " + isMale);
+
+ dis.close();
+ }
}
diff --git a/src/main/java/Advances/InstantApi/demo1.java b/src/main/java/Advances/InstantApi/demo1.java
index 5c84e271..e0b58936 100644
--- a/src/main/java/Advances/InstantApi/demo1.java
+++ b/src/main/java/Advances/InstantApi/demo1.java
@@ -3,10 +3,9 @@
// https://www.youtube.com/watch?v=Mhi4rGPlUwo&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=485
/** InstantApi demo1 : -> similar as java.util.Date class */
-import org.junit.jupiter.api.Test;
-
import java.time.Instant;
import java.time.ZoneOffset;
+import org.junit.jupiter.api.Test;
public class demo1 {
@Test
diff --git a/src/main/java/Advances/Lambda/demo1.java b/src/main/java/Advances/Lambda/demo1.java
index 9a323f3b..2816d032 100644
--- a/src/main/java/Advances/Lambda/demo1.java
+++ b/src/main/java/Advances/Lambda/demo1.java
@@ -5,63 +5,61 @@
import java.util.Comparator;
import org.junit.jupiter.api.Test;
-/**
- * Lambda expression demo 1
- */
-
+/** Lambda expression demo 1 */
public class demo1 {
- @Test
- public void test1(){
+ @Test
+ public void test1() {
- // v1 : tradition style
- Runnable r1 = new Runnable() {
- @Override
- public void run() {
- System.out.println(">>> I love JP");
- }
+ // v1 : tradition style
+ Runnable r1 =
+ new Runnable() {
+ @Override
+ public void run() {
+ System.out.println(">>> I love JP");
+ }
};
- r1.run();
+ r1.run();
- System.out.println("================");
+ System.out.println("================");
- // v2 : lambda style
- // "->" : lambda expression
- Runnable r2 = () -> System.out.println(">>> I love UK");
+ // v2 : lambda style
+ // "->" : lambda expression
+ Runnable r2 = () -> System.out.println(">>> I love UK");
- r2.run();
- }
+ r2.run();
+ }
- @Test
- public void test2(){
+ @Test
+ public void test2() {
- // v1 : tradition style
- Comparator com1 = new Comparator() {
- @Override
- public int compare(Integer o1, Integer o2) {
- return Integer.compare(o1, o2);
- }
+ // v1 : tradition style
+ Comparator com1 =
+ new Comparator() {
+ @Override
+ public int compare(Integer o1, Integer o2) {
+ return Integer.compare(o1, o2);
+ }
};
- int compare1 = com1.compare(12,99);
- System.out.println(">>> compare1 = " + compare1);
-
- System.out.println("================");
+ int compare1 = com1.compare(12, 99);
+ System.out.println(">>> compare1 = " + compare1);
- // v2 : lambda style
- Comparator com2 = (o1, o2) -> Integer.compare(o1, o2);
+ System.out.println("================");
- int compare2 = com2.compare(100,-1);
- System.out.println(">>> compare2 = " + compare2);
+ // v2 : lambda style
+ Comparator com2 = (o1, o2) -> Integer.compare(o1, o2);
- System.out.println("================");
+ int compare2 = com2.compare(100, -1);
+ System.out.println(">>> compare2 = " + compare2);
- // v3 : lambda style II
- Comparator com3 = Integer :: compare;
+ System.out.println("================");
- int compare3 = com3.compare(100,-1);
- System.out.println(">>> compare3 = " + compare3);
- }
+ // v3 : lambda style II
+ Comparator com3 = Integer::compare;
+ int compare3 = com3.compare(100, -1);
+ System.out.println(">>> compare3 = " + compare3);
+ }
}
diff --git a/src/main/java/Advances/Lambda/demo2.java b/src/main/java/Advances/Lambda/demo2.java
index ab821359..543f7551 100644
--- a/src/main/java/Advances/Lambda/demo2.java
+++ b/src/main/java/Advances/Lambda/demo2.java
@@ -10,201 +10,191 @@
import org.junit.jupiter.api.Test;
/**
- * Lambda expression demo 2
+ * Lambda expression demo 2
*
- * 0) lambda expression = functional interface instance
+ * 0) lambda expression = functional interface instance
*
- * 1) example 1: (o1, o2) -> Integer.compare(o1, o2);
+ *
1) example 1: (o1, o2) -> Integer.compare(o1, o2);
*
- * 2) format:
- * -> : lambda operator
- * "left -> " :
- * - lambda param (abstract method param)
- * - class type can be omitted (type inference (類型推斷))
- * - ( if there is only one param, bracket can be omitted as well)
- * "-> right" :
- * - lambda body (overridden abstract method body)
- * - should use a big bracket ({})
- * - if only one line lambda body, return, and bracket can be omitted
+ *
2) format: -> : lambda operator "left -> " : - lambda param (abstract method param) - class
+ * type can be omitted (type inference (類型推斷)) - ( if there is only one param, bracket can be
+ * omitted as well) "-> right" : - lambda body (overridden abstract method body) - should use a big
+ * bracket ({}) - if only one line lambda body, return, and bracket can be omitted
*
- * 3) lambda expression : (6 form)
- * -> form 1) No param, No return value
- * -> form 2) need one param, No return value
- * -> form 3) omit data type, use type inference (類型推斷)
- * -> form 4) if only one param, param bracket can be omitted
- * -> form 5) two or more params, have return value
- * -> form 6) if only one line lambda body, return, and bracket can be omitted
+ *
3) lambda expression : (6 form) -> form 1) No param, No return value -> form 2) need one
+ * param, No return value -> form 3) omit data type, use type inference (類型推斷) -> form 4) if only
+ * one param, param bracket can be omitted -> form 5) two or more params, have return value -> form
+ * 6) if only one line lambda body, return, and bracket can be omitted
*
- * 4) (java only) lambda essence : as (functional) interface instance
+ *
4) (java only) lambda essence : as (functional) interface instance
*
- * 5) what's functional interface instance ?
- * -> if there is ONLY ONE abstract method declared in an interface
- * -> this is a functional interface.
- * -> usually has "@FunctionalInterface" annotation (optional)
- * -> plz check example : Advances.Lambda.MyInterface.java
- * -> can create its instance via lambda expression
- * -> java8 defines lots of functional interfaces at java.util.function pkg
+ *
5) what's functional interface instance ? -> if there is ONLY ONE abstract method declared in
+ * an interface -> this is a functional interface. -> usually has "@FunctionalInterface" annotation
+ * (optional) -> plz check example : Advances.Lambda.MyInterface.java -> can create its instance via
+ * lambda expression -> java8 defines lots of functional interfaces at java.util.function pkg
*
- * 6) OOP (物件導向編程) VS OOF (函數式編程)
- * -> at general OOF, method is 1st tier.
- * -> However, in java, lambda expression is STILL an object
- * -> it belongs a special type -- functional interface
+ *
6) OOP (物件導向編程) VS OOF (函數式編程) -> at general OOF, method is 1st tier. -> However, in java,
+ * lambda expression is STILL an object -> it belongs a special type -- functional interface
*
- * 7) all anonymous classes can be implemented via lambda expression
+ *
7) all anonymous classes can be implemented via lambda expression
*/
-
public class demo2 {
- /** form 1) No param, No return value */
- @Test
- public void test1(){
-
- // v1 : tradition style
- Runnable r1 = new Runnable() {
- @Override
- public void run() {
- System.out.println(">>> I love JP");
- }
+ /** form 1) No param, No return value */
+ @Test
+ public void test1() {
+
+ // v1 : tradition style
+ Runnable r1 =
+ new Runnable() {
+ @Override
+ public void run() {
+ System.out.println(">>> I love JP");
+ }
};
- r1.run();
+ r1.run();
- System.out.println("================");
+ System.out.println("================");
- // v2 : lambda style
- // "->" : lambda expression
- Runnable r2 = () -> {
- System.out.println(">>> I love UK");
+ // v2 : lambda style
+ // "->" : lambda expression
+ Runnable r2 =
+ () -> {
+ System.out.println(">>> I love UK");
};
- r2.run();
-
- }
+ r2.run();
+ }
- /** form 2) need one param, No return value */
- @Test
- public void test2(){
+ /** form 2) need one param, No return value */
+ @Test
+ public void test2() {
- // v1 : tradition style
- Consumer con = new Consumer() {
- @Override
- public void accept(String s) {
- System.out.println(s);
- }
+ // v1 : tradition style
+ Consumer con =
+ new Consumer() {
+ @Override
+ public void accept(String s) {
+ System.out.println(s);
+ }
};
- con.accept("xxx");
+ con.accept("xxx");
- System.out.println("================");
+ System.out.println("================");
- // v2 : lambda style
- Consumer con2 = (String s) -> {
- System.out.println(s);
+ // v2 : lambda style
+ Consumer con2 =
+ (String s) -> {
+ System.out.println(s);
};
- con2.accept("yyy");
+ con2.accept("yyy");
+ }
- }
+ /** form 3) omit data type, use type inference (類型推斷) */
+ @Test
+ public void test3() {
- /** form 3) omit data type, use type inference (類型推斷) */
- @Test
- public void test3(){
-
- // v1 : lambda expression I
- Consumer con1 = (String s) -> {
- System.out.println(s);
+ // v1 : lambda expression I
+ Consumer con1 =
+ (String s) -> {
+ System.out.println(s);
};
- // v2 : lambda expression II : use type inference
- Consumer con2 = (s) -> { // omit "s" 's type
- System.out.println(s);
+ // v2 : lambda expression II : use type inference
+ Consumer con2 =
+ (s) -> { // omit "s" 's type
+ System.out.println(s);
};
- System.out.println("======= Review : type inference ========");
+ System.out.println("======= Review : type inference ========");
- // example 1
- ArrayList list = new ArrayList<>(); // ArrayList<>, type inference
+ // example 1
+ ArrayList list = new ArrayList<>(); // ArrayList<>, type inference
- // example 2
- int[] arr1 = new int[]{1,2,3};
- // is same as below
- int[] arr2 = {1,2,3}; // type inference
- }
+ // example 2
+ int[] arr1 = new int[] {1, 2, 3};
+ // is same as below
+ int[] arr2 = {1, 2, 3}; // type inference
+ }
- /** form 4) if only one param, param bracket can be omitted */
- @Test
- public void test4(){
+ /** form 4) if only one param, param bracket can be omitted */
+ @Test
+ public void test4() {
- // v1 : lambda expression
- Consumer con2 = (s) -> { // omit s's type
- System.out.println(s);
+ // v1 : lambda expression
+ Consumer con2 =
+ (s) -> { // omit s's type
+ System.out.println(s);
};
- con2.accept("zzzz");
- System.out.println("================");
+ con2.accept("zzzz");
+ System.out.println("================");
- // v2 : lambda expression II
- Consumer con3 = s -> { // omit s's type
- System.out.println(s);
+ // v2 : lambda expression II
+ Consumer con3 =
+ s -> { // omit s's type
+ System.out.println(s);
};
- }
-
- /** form 5) two or more params, have return value */
- @Test
- public void test5(){
-
- // v1 : tradition style
- Comparator com1 = new Comparator() {
- @Override
- public int compare(Integer o1, Integer o2) {
- System.out.println(o1);
- System.out.println(o2);
- return o1.compareTo(o2);
- }
- };
-
- System.out.println(com1.compare(100, 200));
-
- System.out.println("=================");
+ }
- // v2 : lambda style
- Comparator com2 = (o1, o2) -> {
+ /** form 5) two or more params, have return value */
+ @Test
+ public void test5() {
+ // v1 : tradition style
+ Comparator com1 =
+ new Comparator() {
+ @Override
+ public int compare(Integer o1, Integer o2) {
System.out.println(o1);
System.out.println(o2);
return o1.compareTo(o2);
+ }
};
- System.out.println(com2.compare(-1, -2));
+ System.out.println(com1.compare(100, 200));
- }
+ System.out.println("=================");
- /** form 6) if only one line lambda body, return bracket can be omitted */
- @Test
- public void test6(){
-
- // v1 : lambda style
- Comparator com2 = (o1, o2) -> {
- return o1.compareTo(o2);
+ // v2 : lambda style
+ Comparator com2 =
+ (o1, o2) -> {
+ System.out.println(o1);
+ System.out.println(o2);
+ return o1.compareTo(o2);
};
- // v2 : lambda style II
- Comparator com3 = (o1, o2) -> o1.compareTo(o2);
+ System.out.println(com2.compare(-1, -2));
+ }
- }
+ /** form 6) if only one line lambda body, return bracket can be omitted */
+ @Test
+ public void test6() {
- // form 6) advanced demo
- @Test
- public void test7(){
-
- // v1 : lambda expression
- Consumer con3 = s -> { // omit s's type
- System.out.println(s);
+ // v1 : lambda style
+ Comparator com2 =
+ (o1, o2) -> {
+ return o1.compareTo(o2);
};
- // v2 : lambda expression II
- Consumer con4 = s -> System.out.println(s);
+ // v2 : lambda style II
+ Comparator com3 = (o1, o2) -> o1.compareTo(o2);
+ }
- }
+ // form 6) advanced demo
+ @Test
+ public void test7() {
+
+ // v1 : lambda expression
+ Consumer con3 =
+ s -> { // omit s's type
+ System.out.println(s);
+ };
+ // v2 : lambda expression II
+ Consumer con4 = s -> System.out.println(s);
+ }
}
diff --git a/src/main/java/Advances/Lambda/demo3.java b/src/main/java/Advances/Lambda/demo3.java
index d96774bb..80c8b2a7 100644
--- a/src/main/java/Advances/Lambda/demo3.java
+++ b/src/main/java/Advances/Lambda/demo3.java
@@ -10,92 +10,98 @@
import org.junit.jupiter.api.Test;
/**
- * Lambda expression demo 3
+ * Lambda expression demo 3
*
- * - Java's default 4 functional interfaces
+ * - Java's default 4 functional interfaces
*
- * - 1) Consumer interface :
- * Consumer void accept(T t)
+ * - 1) Consumer interface : Consumer void accept(T t)
*
- * - 2) Supplier interface:
- * Supplier T get()
+ * - 2) Supplier interface: Supplier T get()
*
- * - 3) Function interface:
- * Function R Apply(T t)
+ * - 3) Function interface: Function R Apply(T t)
*
- * - 4) Predicate (斷言) interface:
- * Predicate boolean test(T t)
+ * - 4) Predicate (斷言) interface: Predicate boolean test(T t)
*/
-
public class demo3 {
- @Test
- public void test1(){
-
- // V1 : tradition way
- happyTime(500, new Consumer() {
- @Override
- public void accept(Double aDouble) {
- System.out.println(">>> have some happy hour, spend " + aDouble);
- }
+ @Test
+ public void test1() {
+
+ // V1 : tradition way
+ happyTime(
+ 500,
+ new Consumer() {
+ @Override
+ public void accept(Double aDouble) {
+ System.out.println(">>> have some happy hour, spend " + aDouble);
+ }
});
- System.out.println("=====================");
-
- // V2 : lambda expression
- happyTime(400, money -> {System.out.println(">>> have some happy hour, spend " + money);});
-
- System.out.println("=====================");
-
- // V3 : lambda expression II
- happyTime(400, money -> System.out.println(">>> have some happy hour, spend " + money));
-
- }
-
- public void happyTime(double money, Consumer con){
- con.accept(money);
- }
+ System.out.println("=====================");
- @Test
- public void test2(){
-
- // V1 : tradition way
- List list = Arrays.asList("UK", "US", "JP", "TW", "UN");
- List r1 = filterString(list, new Predicate() {
- @Override
- public boolean test(String s) {
- return s.contains("U");
- }
+ // V2 : lambda expression
+ happyTime(
+ 400,
+ money -> {
+ System.out.println(">>> have some happy hour, spend " + money);
});
- System.out.println("r1 = " + r1);
-
- System.out.println("=====================");
-
- // V2 : lambda expression
- List r2 = filterString(list, s -> {return s.contains("U");});
- System.out.println("r2 = " + r2);
+ System.out.println("=====================");
- // V3 : lambda expression II
- List r3 = filterString(list, s -> s.contains("U"));
- System.out.println("r3 = " + r3);
+ // V3 : lambda expression II
+ happyTime(400, money -> System.out.println(">>> have some happy hour, spend " + money));
+ }
- }
-
- // method for test
- // based on condition, filter out string in array,
- // the condition is defined by Predicate method
- public List filterString(List list, Predicate pre){
+ public void happyTime(double money, Consumer con) {
+ con.accept(money);
+ }
- ArrayList filterList = new ArrayList<>();
+ @Test
+ public void test2() {
- for (String s : list){
- if (pre.test(s)){
- filterList.add(s);
- }
- }
-
- return filterList;
+ // V1 : tradition way
+ List list = Arrays.asList("UK", "US", "JP", "TW", "UN");
+ List r1 =
+ filterString(
+ list,
+ new Predicate() {
+ @Override
+ public boolean test(String s) {
+ return s.contains("U");
+ }
+ });
+
+ System.out.println("r1 = " + r1);
+
+ System.out.println("=====================");
+
+ // V2 : lambda expression
+ List r2 =
+ filterString(
+ list,
+ s -> {
+ return s.contains("U");
+ });
+ System.out.println("r2 = " + r2);
+
+ // V3 : lambda expression II
+ List r3 = filterString(list, s -> s.contains("U"));
+ System.out.println("r3 = " + r3);
+ }
+
+ // method for test
+ // based on condition, filter out string in array,
+ // the condition is defined by Predicate method
+ public List filterString(List list, Predicate pre) {
+
+ ArrayList filterList = new ArrayList<>();
+
+ for (String s : list) {
+ if (pre.test(s)) {
+ filterList.add(s);
+ }
}
+ return filterList;
+ }
}
diff --git a/src/main/java/Advances/Lambda/demo4/ConstructorRefTest.java b/src/main/java/Advances/Lambda/demo4/ConstructorRefTest.java
index 06284ea1..83c7aca8 100644
--- a/src/main/java/Advances/Lambda/demo4/ConstructorRefTest.java
+++ b/src/main/java/Advances/Lambda/demo4/ConstructorRefTest.java
@@ -9,100 +9,86 @@
import org.junit.jupiter.api.Test;
/**
- * Constructor Ref demo 1
+ * Constructor Ref demo 1
*
- * 1) Constructor ref
- * -> similar as "method ref"
- * -> lambda expression abstract method's args have to be AS SAME AS Constructor's args
- * -> lambda expression return type is SAME as Constructor's type
+ * 1) Constructor ref -> similar as "method ref" -> lambda expression abstract method's args have
+ * to be AS SAME AS Constructor's args -> lambda expression return type is SAME as Constructor's
+ * type
*
- * 2) array ref
- * -> recognize array as a "special class", so use case is similar as "constructor ref"
+ *
2) array ref -> recognize array as a "special class", so use case is similar as "constructor
+ * ref"
*/
-
public class ConstructorRefTest {
- /**
- * Example 1
- * -> Supplier's T get()
- * -> Employee's null arg constructor : Employee()
- * -> since T get() has no arg, has return val
- * -> and Employee has null arg constructor : Employee()
- * -> so we can recognize "Employee()" as a method
- */
- @Test
- public void test1(){
-
- // V0 : tradition version
- Supplier sup = new Supplier() {
- @Override
- public Employee get() {
- return new Employee();
- }
+ /**
+ * Example 1 -> Supplier's T get() -> Employee's null arg constructor : Employee() -> since T
+ * get() has no arg, has return val -> and Employee has null arg constructor : Employee() -> so we
+ * can recognize "Employee()" as a method
+ */
+ @Test
+ public void test1() {
+
+ // V0 : tradition version
+ Supplier sup =
+ new Supplier() {
+ @Override
+ public Employee get() {
+ return new Employee();
+ }
};
- // V1 : lambda expression
- Supplier sup1 = () -> new Employee();
- System.out.println(sup1.get());
-
- // V2 : constructor ref
- Supplier sup2 = Employee :: new;
- }
-
- /**
- * Example 2
- * -> Function's R apply(T t)
- */
- @Test
- public void test2(){
-
- // V1 : lambda expression
- Function func1 = id -> new Employee(id);
- Employee emp1 = func1.apply(1001);
- System.out.println(emp1);
-
- System.out.println("===============");
-
- // V2 : constructor ref
- Function func2 = Employee :: new;
- Employee emp2 = func1.apply(1002);
- System.out.println(func1.apply(1002));
- System.out.println(emp2);
- System.out.println(emp2.getId());
- }
-
- /**
- * Example 3
- * -> BiFunction's R apply(T t, U u)
- */
- @Test
- public void test3(){
-
- // V1 : lambda expression
- BiFunction func1 = (id, name) -> new Employee(id, name);
- System.out.println(func1.apply(99, "lynn"));
-
- // V2 : constructor ref
- BiFunction func2 = Employee :: new;
- System.out.println(func2.apply(99, "lynn"));
- }
-
- /**
- * Example 4 : Array reference
- * -> Function's apply(T t)
- */
- @Test
- public void test4(){
-
- // V1 : lambda expression
- Function func1 = length -> new String[length];
- String[] arr1 = func1.apply(5);
- System.out.println(Arrays.toString(arr1));
-
- // V2 : Array ref
- Function func2 = String[] :: new;
- String[] arr2 = func1.apply(10);
- System.out.println(Arrays.toString(arr2));
- }
-
+ // V1 : lambda expression
+ Supplier sup1 = () -> new Employee();
+ System.out.println(sup1.get());
+
+ // V2 : constructor ref
+ Supplier sup2 = Employee::new;
+ }
+
+ /** Example 2 -> Function's R apply(T t) */
+ @Test
+ public void test2() {
+
+ // V1 : lambda expression
+ Function func1 = id -> new Employee(id);
+ Employee emp1 = func1.apply(1001);
+ System.out.println(emp1);
+
+ System.out.println("===============");
+
+ // V2 : constructor ref
+ Function func2 = Employee::new;
+ Employee emp2 = func1.apply(1002);
+ System.out.println(func1.apply(1002));
+ System.out.println(emp2);
+ System.out.println(emp2.getId());
+ }
+
+ /** Example 3 -> BiFunction's R apply(T t, U u) */
+ @Test
+ public void test3() {
+
+ // V1 : lambda expression
+ BiFunction func1 = (id, name) -> new Employee(id, name);
+ System.out.println(func1.apply(99, "lynn"));
+
+ // V2 : constructor ref
+ BiFunction func2 = Employee::new;
+ System.out.println(func2.apply(99, "lynn"));
+ }
+
+ /** Example 4 : Array reference -> Function's apply(T t) */
+ @Test
+ public void test4() {
+
+ // V1 : lambda expression
+ Function func1 = length -> new String[length];
+ String[] arr1 = func1.apply(5);
+ System.out.println(Arrays.toString(arr1));
+
+ // V2 : Array ref
+ Function func2 = String[]::new;
+ String[] arr2 = func1.apply(10);
+ System.out.println(Arrays.toString(arr2));
+ }
}
diff --git a/src/main/java/Advances/Lambda/demo4/MethodRefTest.java b/src/main/java/Advances/Lambda/demo4/MethodRefTest.java
index 9553c3da..0ec5e237 100644
--- a/src/main/java/Advances/Lambda/demo4/MethodRefTest.java
+++ b/src/main/java/Advances/Lambda/demo4/MethodRefTest.java
@@ -4,14 +4,13 @@
// https://www.youtube.com/watch?v=jVfmtHhrKgA&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=672
// https://www.youtube.com/watch?v=0lufoYMLsF4&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=674
-import org.junit.jupiter.api.Test;
-
import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
+import org.junit.jupiter.api.Test;
/**
* Method reference demo 1
@@ -90,7 +89,7 @@ public void test3() {
Comparator com2 =
Integer
::compare; // NOTE : we DON'T need to have param (t1, t2) here, since the method we use
- // here is AS SAME AS the lambda expression it refers
+ // here is AS SAME AS the lambda expression it refers
System.out.println(com2.compare(1, 100));
}
diff --git a/src/main/java/Advances/LocalDateTime/demo1.java b/src/main/java/Advances/LocalDateTime/demo1.java
index 463fe6d7..4774838b 100644
--- a/src/main/java/Advances/LocalDateTime/demo1.java
+++ b/src/main/java/Advances/LocalDateTime/demo1.java
@@ -10,62 +10,61 @@
/**
* LocalDate, LocalTime, LocalDateTime demo 1
*
- * 1) LocalDateTime used more often than LocalDate, LocalDateTime
+ * 1) LocalDateTime used more often than LocalDate, LocalDateTime
*
- * 2) LocalDate, LocalTime, LocalDateTime are UNCHANGEABLE
+ *
2) LocalDate, LocalTime, LocalDateTime are UNCHANGEABLE
*
- * 3) similar to Calendar class
+ *
3) similar to Calendar class
*/
-
public class demo1 {
- @Test
- public void test1(){
- // now() : get current date, time, or date+time
- LocalDate localDate = LocalDate.now();
- LocalTime localTime = LocalTime.now();
- LocalDateTime localDateTime = LocalDateTime.now();
+ @Test
+ public void test1() {
+ // now() : get current date, time, or date+time
+ LocalDate localDate = LocalDate.now();
+ LocalTime localTime = LocalTime.now();
+ LocalDateTime localDateTime = LocalDateTime.now();
- System.out.println(localDate);
- System.out.println(localTime);
- System.out.println(localDateTime);
+ System.out.println(localDate);
+ System.out.println(localTime);
+ System.out.println(localDateTime);
- System.out.println("--------------------");
+ System.out.println("--------------------");
- // of() : we can define year, month, day... WITHOUT OFFSET
- LocalDateTime localDateTime1 = LocalDateTime.of(2021,01,01,00,10,10);
+ // of() : we can define year, month, day... WITHOUT OFFSET
+ LocalDateTime localDateTime1 = LocalDateTime.of(2021, 01, 01, 00, 10, 10);
- System.out.println(localDateTime1);
+ System.out.println(localDateTime1);
- System.out.println("--------------------");
+ System.out.println("--------------------");
- // getXXX()
- System.out.println(localDateTime.getYear());
- System.out.println(localDateTime.getMonth());
- System.out.println(localDateTime.getMinute());
- System.out.println(localDateTime.getDayOfMonth());
+ // getXXX()
+ System.out.println(localDateTime.getYear());
+ System.out.println(localDateTime.getMonth());
+ System.out.println(localDateTime.getMinute());
+ System.out.println(localDateTime.getDayOfMonth());
- System.out.println("--------------------");
+ System.out.println("--------------------");
- // with()
- // LocalDate, LocalTime, LocalDateTime are UNCHANGEABLE
- System.out.println(localDateTime.getDayOfMonth());
- LocalDateTime localDateTime2 = localDateTime.withDayOfMonth(22);
- System.out.println(localDateTime2.getDayOfMonth());
+ // with()
+ // LocalDate, LocalTime, LocalDateTime are UNCHANGEABLE
+ System.out.println(localDateTime.getDayOfMonth());
+ LocalDateTime localDateTime2 = localDateTime.withDayOfMonth(22);
+ System.out.println(localDateTime2.getDayOfMonth());
- System.out.println("--------------------");
+ System.out.println("--------------------");
- // plus()
- // UNCHANGEABLE
- System.out.println(localDateTime);
- LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
- System.out.println(localDateTime3);
+ // plus()
+ // UNCHANGEABLE
+ System.out.println(localDateTime);
+ LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
+ System.out.println(localDateTime3);
- System.out.println("--------------------");
+ System.out.println("--------------------");
- // minus
- // UNCHANGEABLE
- System.out.println(localDateTime);
- LocalDateTime localDateTime4 = localDateTime.minusMonths(3);
- System.out.println(localDateTime4);
- }
+ // minus
+ // UNCHANGEABLE
+ System.out.println(localDateTime);
+ LocalDateTime localDateTime4 = localDateTime.minusMonths(3);
+ System.out.println(localDateTime4);
+ }
}
diff --git a/src/main/java/Advances/MapDemo/demo1.java b/src/main/java/Advances/MapDemo/demo1.java
index 44c87d72..e9b816bb 100644
--- a/src/main/java/Advances/MapDemo/demo1.java
+++ b/src/main/java/Advances/MapDemo/demo1.java
@@ -7,12 +7,11 @@
// https://www.youtube.com/watch?v=y-MDDtzyjKE&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=552
// https://www.youtube.com/watch?v=8_yeocWxCqU&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=553
-import org.junit.jupiter.api.Test;
-
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.Map;
+import org.junit.jupiter.api.Test;
/** Map demo 1 : concepts, properties */
diff --git a/src/main/java/Advances/MapDemo/demo2.java b/src/main/java/Advances/MapDemo/demo2.java
index 3195fddd..152d748f 100644
--- a/src/main/java/Advances/MapDemo/demo2.java
+++ b/src/main/java/Advances/MapDemo/demo2.java
@@ -4,9 +4,8 @@
// https://www.youtube.com/watch?v=OmWTqukxSzU&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=555
/** Map demo 2 : methods */
-import org.junit.jupiter.api.Test;
-
import java.util.*;
+import org.junit.jupiter.api.Test;
/**
* Map : double array data structure -> key-value record
diff --git a/src/main/java/Advances/ObjectInputOutputFlow/demo1.java b/src/main/java/Advances/ObjectInputOutputFlow/demo1.java
index 560f3f48..8c734d01 100644
--- a/src/main/java/Advances/ObjectInputOutputFlow/demo1.java
+++ b/src/main/java/Advances/ObjectInputOutputFlow/demo1.java
@@ -6,81 +6,78 @@
import org.junit.jupiter.api.Test;
/**
- * Object Flow demo 1 : `serialization`, `deserialization` basic
+ * Object Flow demo 1 : `serialization`, `deserialization` basic
*
- * 1) ObjectInputStream, ObjectOutputStream
- * 2) purpose : can save, read, transform java instance <----> data flow
- * 3) serialization
- * 4) deserialization
- * 5) NOTE !!! : if we want a java class serializable, it needs below conditions (check Advances.ObjectInputOutputFlow.Person.java)
+ *
1) ObjectInputStream, ObjectOutputStream 2) purpose : can save, read, transform java instance
+ * <----> data flow 3) serialization 4) deserialization 5) NOTE !!! : if we want a java class
+ * serializable, it needs below conditions (check Advances.ObjectInputOutputFlow.Person.java)
*/
-
public class demo1 {
- /**
- * demo 1
- * serialization : transform in-memory java instance into hard disk or send via internet
- * will use ObjectOutputStream
- */
- @Test
- public void test1() {
- ObjectOutputStream oos = null;
- try{
- // step 1) create flow, instance
- oos = new ObjectOutputStream(new FileOutputStream("src/main/java/Advances/ObjectInputOutputFlow/output.txt"));
+ /**
+ * demo 1 serialization : transform in-memory java instance into hard disk or send via internet
+ * will use ObjectOutputStream
+ */
+ @Test
+ public void test1() {
+ ObjectOutputStream oos = null;
+ try {
+ // step 1) create flow, instance
+ oos =
+ new ObjectOutputStream(
+ new FileOutputStream("src/main/java/Advances/ObjectInputOutputFlow/output.txt"));
- // step 2) write data
- oos.writeObject(new String("London Tokyo NewYork"));
+ // step 2) write data
+ oos.writeObject("London Tokyo NewYork");
- // step 3) flush memory (so every write op will be reflected to output file)
- oos.flush();
- }catch (IOException e){
- e.printStackTrace();
- }finally {
- // step 4) close resources
- if (oos != null){
- try{
- oos.close();
- }
- catch (IOException e){
- e.printStackTrace();
- }
- }
+ // step 3) flush memory (so every write op will be reflected to output file)
+ oos.flush();
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ // step 4) close resources
+ if (oos != null) {
+ try {
+ oos.close();
+ } catch (IOException e) {
+ e.printStackTrace();
}
+ }
}
+ }
+ /**
+ * demo 2 deserialization : transform hard disk / internet data to java instance will use
+ * ObjectInputStream
+ */
+ @Test
+ public void test2() throws IOException, ClassNotFoundException {
- /**
- * demo 2
- * deserialization : transform hard disk / internet data to java instance
- * will use ObjectInputStream
- */
- @Test
- public void test2() throws IOException, ClassNotFoundException {
-
- ObjectInputStream ois = null;
+ ObjectInputStream ois = null;
- try{
+ try {
- // step 1)
- ois = new ObjectInputStream(new FileInputStream("src/main/java/Advances/ObjectInputOutputFlow/output.txt"));
+ // step 1)
+ ois =
+ new ObjectInputStream(
+ new FileInputStream("src/main/java/Advances/ObjectInputOutputFlow/output.txt"));
- // step 2)
- Object obj = ois.readObject();
- // transform it into string, since we know it's string data type
- String str = (String) obj;
- System.out.println(str);
+ // step 2)
+ Object obj = ois.readObject();
+ // transform it into string, since we know it's string data type
+ String str = (String) obj;
+ System.out.println(str);
- }catch (Exception e){
- e.printStackTrace();
- }finally {
- // step 3)
- if (ois != null){
- try{
- ois.close();
- }catch (Exception e){
- e.printStackTrace();
- }
- }
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ // step 3)
+ if (ois != null) {
+ try {
+ ois.close();
+ } catch (Exception e) {
+ e.printStackTrace();
}
+ }
}
+ }
}
diff --git a/src/main/java/Advances/ObjectInputOutputFlow/demo2.java b/src/main/java/Advances/ObjectInputOutputFlow/demo2.java
index 71fc675c..71ac78a0 100644
--- a/src/main/java/Advances/ObjectInputOutputFlow/demo2.java
+++ b/src/main/java/Advances/ObjectInputOutputFlow/demo2.java
@@ -3,87 +3,89 @@
// https://www.youtube.com/watch?v=F7FPaVlGhhc&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=611
/**
- * Object Flow demo 2 : `serialization`, `deserialization` with custom java class
+ * Object Flow demo 2 : `serialization`, `deserialization` with custom java class
*
- * NOTE !!! : if we want a java class serializable, it needs below conditions (check Advances.ObjectInputOutputFlow.Person.java)
+ *
NOTE !!! : if we want a java class serializable, it needs below conditions (check
+ * Advances.ObjectInputOutputFlow.Person.java)
*/
-
import java.io.*;
import org.junit.jupiter.api.Test;
public class demo2 {
- @Test
- public void test1() {
- ObjectOutputStream oos = null;
- try{
- // step 1) create flow, instance
- oos = new ObjectOutputStream(new FileOutputStream("src/main/java/Advances/ObjectInputOutputFlow/output2.txt"));
-
- // step 2) write data
- oos.writeObject(new String("London Tokyo NewYork"));
-
- // step 3) flush memory (so every write op will be reflected to output file)
- oos.flush();
-
- // NOTE : we have to make Person class serializable, or will face "java.io.NotSerializableException: Advances.ObjectInputOutputFlow.Person" exception
- oos.writeObject(new Person("amy", 17));
- oos.flush();
-
- }catch (IOException e){
- e.printStackTrace();
- }finally {
- // step 4) close resources
- if (oos != null){
- try{
- oos.close();
- }
- catch (IOException e){
- e.printStackTrace();
- }
- }
+ @Test
+ public void test1() {
+ ObjectOutputStream oos = null;
+ try {
+ // step 1) create flow, instance
+ oos =
+ new ObjectOutputStream(
+ new FileOutputStream("src/main/java/Advances/ObjectInputOutputFlow/output2.txt"));
+
+ // step 2) write data
+ oos.writeObject("London Tokyo NewYork");
+
+ // step 3) flush memory (so every write op will be reflected to output file)
+ oos.flush();
+
+ // NOTE : we have to make Person class serializable, or will face
+ // "java.io.NotSerializableException: Advances.ObjectInputOutputFlow.Person" exception
+ oos.writeObject(new Person("amy", 17));
+ oos.flush();
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ // step 4) close resources
+ if (oos != null) {
+ try {
+ oos.close();
+ } catch (IOException e) {
+ e.printStackTrace();
}
+ }
}
-
-
- /**
- * demo 2
- * deserialization : transform hard disk / internet data to java instance
- * will use ObjectInputStream
- */
- @Test
- public void test2() throws IOException, ClassNotFoundException {
-
- ObjectInputStream ois = null;
-
- try{
-
- // step 1)
- ois = new ObjectInputStream(new FileInputStream("src/main/java/Advances/ObjectInputOutputFlow/output2.txt"));
-
- // step 2)
- Object obj = ois.readObject();
-
- // NOTE : read data type should align with write data type
- // read string : transform it into string, since we know it's string data type
- String str = (String) obj;
- System.out.println(str);
-
- // read Person
- Person p = (Person) ois.readObject();
- System.out.println(p); //Person{name='amy', age=17}
-
- }catch (Exception e){
- e.printStackTrace();
- }finally {
- // step 3)
- if (ois != null){
- try{
- ois.close();
- }catch (Exception e){
- e.printStackTrace();
- }
- }
+ }
+
+ /**
+ * demo 2 deserialization : transform hard disk / internet data to java instance will use
+ * ObjectInputStream
+ */
+ @Test
+ public void test2() throws IOException, ClassNotFoundException {
+
+ ObjectInputStream ois = null;
+
+ try {
+
+ // step 1)
+ ois =
+ new ObjectInputStream(
+ new FileInputStream("src/main/java/Advances/ObjectInputOutputFlow/output2.txt"));
+
+ // step 2)
+ Object obj = ois.readObject();
+
+ // NOTE : read data type should align with write data type
+ // read string : transform it into string, since we know it's string data type
+ String str = (String) obj;
+ System.out.println(str);
+
+ // read Person
+ Person p = (Person) ois.readObject();
+ System.out.println(p); // Person{name='amy', age=17}
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ // step 3)
+ if (ois != null) {
+ try {
+ ois.close();
+ } catch (Exception e) {
+ e.printStackTrace();
}
+ }
}
+ }
}
diff --git a/src/main/java/Advances/Optional/demo1.java b/src/main/java/Advances/Optional/demo1.java
index 3806e646..a2385b04 100644
--- a/src/main/java/Advances/Optional/demo1.java
+++ b/src/main/java/Advances/Optional/demo1.java
@@ -3,9 +3,8 @@
// https://www.youtube.com/watch?v=MYXoEU3RkG0&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=684
// https://www.youtube.com/watch?v=wOi2k4dJviM&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=684
-import org.junit.jupiter.api.Test;
-
import java.util.Optional;
+import org.junit.jupiter.api.Test;
/**
* Optional demo 1
diff --git a/src/main/java/Advances/RandomAccessFile/demo1.java b/src/main/java/Advances/RandomAccessFile/demo1.java
index d2efe693..4fb30ef8 100644
--- a/src/main/java/Advances/RandomAccessFile/demo1.java
+++ b/src/main/java/Advances/RandomAccessFile/demo1.java
@@ -9,116 +9,117 @@
import org.junit.jupiter.api.Test;
/**
- * RandomAccessFile demo 1
+ * RandomAccessFile demo 1
*
- * 1) RandomAccessFile is directly below java.lang.Object class,
- * implement DataInput, DataOutput interface
+ *
1) RandomAccessFile is directly below java.lang.Object class, implement DataInput, DataOutput
+ * interface
*
- * 2) RandomAccessFile can be BOTH input, and output flow
- * (but have to init 2 java instances)
+ *
2) RandomAccessFile can be BOTH input, and output flow (but have to init 2 java instances)
*
- * 3) while RandomAccessFile DataOutput,
- * 3-1) if output file not existed, RandomAccessFile will automatically make a new one
- * 3-2) if output file already existed, will OVERWRITE original file (write from beginning)
- *
- * 4) can do "file insert" via RandomAccessFile
- * (can add data to file with specific idx (not only at beginning/end or replace))
+ *
3) while RandomAccessFile DataOutput, 3-1) if output file not existed, RandomAccessFile will
+ * automatically make a new one 3-2) if output file already existed, will OVERWRITE original file
+ * (write from beginning)
*
+ *
4) can do "file insert" via RandomAccessFile (can add data to file with specific idx (not only
+ * at beginning/end or replace))
*/
public class demo1 {
- @Test
- public void test1() throws IOException {
- RandomAccessFile raf1 = null;
- RandomAccessFile raf2 = null;
- try{
-
- // step 1)
- raf1 = new RandomAccessFile(new File("src/main/java/Advances/RandomAccessFile/input1.txt"),"r");
- raf2 = new RandomAccessFile(new File("src/main/java/Advances/RandomAccessFile/output1.txt"),"rw");
-
- // step 2)
- byte[] buffer = new byte[1024];
- int len;
- while ((len = raf1.read(buffer)) != -1){
- raf2.write(buffer, 0, len);
- }
-
- }catch (Exception e){
- e.printStackTrace();
- }finally {
-
- // step 3)
- if (raf1 != null){
- try{
- raf1.close();
- }catch (Exception e){
- e.printStackTrace();
- }
- }
-
- if (raf2 != null){
- try{
- raf2.close();
- }catch (Exception e){
- e.printStackTrace();
- }
- }
+ @Test
+ public void test1() throws IOException {
+ RandomAccessFile raf1 = null;
+ RandomAccessFile raf2 = null;
+ try {
+
+ // step 1)
+ raf1 =
+ new RandomAccessFile(new File("src/main/java/Advances/RandomAccessFile/input1.txt"), "r");
+ raf2 =
+ new RandomAccessFile(
+ new File("src/main/java/Advances/RandomAccessFile/output1.txt"), "rw");
+
+ // step 2)
+ byte[] buffer = new byte[1024];
+ int len;
+ while ((len = raf1.read(buffer)) != -1) {
+ raf2.write(buffer, 0, len);
+ }
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+
+ // step 3)
+ if (raf1 != null) {
+ try {
+ raf1.close();
+ } catch (Exception e) {
+ e.printStackTrace();
}
- }
+ }
+ if (raf2 != null) {
+ try {
+ raf2.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
- @Test
- public void test2() throws IOException {
- RandomAccessFile raf1 = null;
+ @Test
+ public void test2() throws IOException {
+ RandomAccessFile raf1 = null;
- raf1 = new RandomAccessFile(new File("src/main/java/Advances/RandomAccessFile/output2.txt"),"rw");
+ raf1 =
+ new RandomAccessFile(new File("src/main/java/Advances/RandomAccessFile/output2.txt"), "rw");
- raf1.write("ababba".getBytes());
+ raf1.write("ababba".getBytes());
- raf1.close();
- }
+ raf1.close();
+ }
+ @Test
+ public void test3() throws IOException {
+ RandomAccessFile raf1 = null;
- @Test
- public void test3() throws IOException {
- RandomAccessFile raf1 = null;
+ raf1 =
+ new RandomAccessFile(new File("src/main/java/Advances/RandomAccessFile/output2.txt"), "rw");
- raf1 = new RandomAccessFile(new File("src/main/java/Advances/RandomAccessFile/output2.txt"),"rw");
+ // move pointer to idx = 3 position
+ raf1.seek(3);
- // move pointer to idx = 3 position
- raf1.seek(3);
+ raf1.write("xyz".getBytes()); // do "insert" like op
- raf1.write("xyz".getBytes()); // do "insert" like op
+ raf1.close();
+ }
- raf1.close();
- }
+ /** do "insert" like op via RandomAccessFile */
+ @Test
+ public void test4() throws IOException {
+ RandomAccessFile raf1 = null;
+ raf1 =
+ new RandomAccessFile(new File("src/main/java/Advances/RandomAccessFile/output2.txt"), "rw");
- /** do "insert" like op via RandomAccessFile */
- @Test
- public void test4() throws IOException {
- RandomAccessFile raf1 = null;
+ // move pointer to idx = 3 position
+ raf1.seek(3);
- raf1 = new RandomAccessFile(new File("src/main/java/Advances/RandomAccessFile/output2.txt"),"rw");
-
- // move pointer to idx = 3 position
- raf1.seek(3);
-
- // save all indices after some character to StringBuilder
- StringBuilder builder = new StringBuilder( (int) new File("input1.txt").length() );
- byte[] buffer = new byte[20];
- int len;
- while ((len=raf1.read(buffer)) != -1){
- builder.append(new String(buffer, 0, len));
- }
+ // save all indices after some character to StringBuilder
+ StringBuilder builder = new StringBuilder((int) new File("input1.txt").length());
+ byte[] buffer = new byte[20];
+ int len;
+ while ((len = raf1.read(buffer)) != -1) {
+ builder.append(new String(buffer, 0, len));
+ }
- // move idx to 3, then write "xyz" in
- raf1.seek(3);
- raf1.write("xyz".getBytes()); // do "insert" like op
+ // move idx to 3, then write "xyz" in
+ raf1.seek(3);
+ raf1.write("xyz".getBytes()); // do "insert" like op
- // write StringBuilder's data into doc
- raf1.write(builder.toString().getBytes());
+ // write StringBuilder's data into doc
+ raf1.write(builder.toString().getBytes());
- raf1.close();
- }
+ raf1.close();
+ }
}
diff --git a/src/main/java/Advances/Reflection/MyAnnotation.java b/src/main/java/Advances/Reflection/MyAnnotation.java
index a062ea58..3095526d 100644
--- a/src/main/java/Advances/Reflection/MyAnnotation.java
+++ b/src/main/java/Advances/Reflection/MyAnnotation.java
@@ -2,12 +2,12 @@
// https://www.youtube.com/watch?v=x6tmNMxMmZo&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=648
+import static java.lang.annotation.ElementType.*;
+
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
-import static java.lang.annotation.ElementType.*;
-
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
diff --git a/src/main/java/Advances/Reflection/demo1.java b/src/main/java/Advances/Reflection/demo1.java
index c961bbdb..e87fa78e 100644
--- a/src/main/java/Advances/Reflection/demo1.java
+++ b/src/main/java/Advances/Reflection/demo1.java
@@ -15,170 +15,151 @@
import org.junit.jupiter.api.Test;
/**
- * Reflection demo 1 : basic
+ * Reflection demo 1 : basic
*
- * 1) main common API
- * - java.lang.Class : represent a class
- * - java.lang.reflect.Method : represent a class method
- * - java.lang.reflect.Field : represent a class attr
- * - java.lang.reflect.Constructor : represent a class constructor
- * ..
+ *
1) main common API - java.lang.Class : represent a class - java.lang.reflect.Method :
+ * represent a class method - java.lang.reflect.Field : represent a class attr -
+ * java.lang.reflect.Constructor : represent a class constructor ..
*
- * 2) Question:
- * 2-1) Reflection conflicts with OOP Encapsulation (封裝) ? explain ?
- * -> NO conflict
- * -> different purposes
+ *
2) Question: 2-1) Reflection conflicts with OOP Encapsulation (封裝) ? explain ? -> NO conflict
+ * -> different purposes
*
+ *
2-2) in general dev, which one we should use ? : "new " or "reflection" ? -> use "new
+ * " is better -> reflection is for "dynamic". so if we are NOT sure which class need to
+ * init, have to decide till runtime -> use "reflection" - example : /login, /add ... endpoints via
+ * java servlet
*
- * 2-2) in general dev, which one we should use ? : "new " or "reflection" ?
- * -> use "new " is better
- * -> reflection is for "dynamic". so if we are NOT sure which class need to init, have to decide till runtime -> use "reflection"
- * - example : /login, /add ... endpoints via java servlet
+ * 3) java.lang.class understanding - 3-1) java class loading steps - 1) java.exe runs, creates
+ * .class (字節碼文件), then use java.exe parses and executes .class file (load .class to memory) - 2) we
+ * call in-memory class above as "run-time class", which is a class instance - 3) running class
+ * instance (in-memory) will be cased in cache (for a period of time)
*
- * 3) java.lang.class understanding
- * - 3-1) java class loading steps
- * - 1) java.exe runs, creates .class (字節碼文件), then use java.exe parses and executes .class file (load .class to memory)
- * - 2) we call in-memory class above as "run-time class", which is a class instance
- * - 3) running class instance (in-memory) will be cased in cache (for a period of time)
+ *
4) So, `Class clazz = Person.class;` -> Class is a "run-time class
*
- * 4) So, `Class clazz = Person.class;`
- * -> Class is a "run-time class
- *
- * 5) in Java, everything is an instance
- *
- * 6) from which class we can get their Class (via reflection)
- * - class (external class, internal static class..)
- * - interface
- * - []
- * - enum
- * - annotation (e.g. @interface..)
- * - primitive type
- * - void
+ *
5) in Java, everything is an instance
*
+ *
6) from which class we can get their Class (via reflection) - class (external class, internal
+ * static class..) - interface - [] - enum - annotation (e.g. @interface..) - primitive type - void
*/
-
public class demo1 {
- /**
- * test 1: Before reflection, op we can do on Person class
- */
- @Test
- public void test1(){
- // 1) create Person class (init)
- Person p1 = new Person("kate",17);
-
- // 2) via instance, use its method
- p1.age = 20;
- System.out.println(p1.toString());
-
- p1.show();
-
- // can't use Person instance's private method, attr.. outside Person class
- }
-
- /**
- * test 2: After reflection, op we can do on Person class
- */
- @Test
- public void test2() throws Exception {
-
- // 1) create an instance via reflection
- Class clazz = Person.class;
- Constructor cons = clazz.getConstructor(String.class, int.class);
-
- Object obj = cons.newInstance("kate", 17);
- System.out.println(obj.toString());
-
- // DownCasting (強轉)
- Person p = (Person) obj;
- System.out.println(p.toString());
-
- // 2) call attr. via reflection
- Field age = clazz.getDeclaredField("age");
- age.set(p, 100);
- System.out.println(p.toString());
-
- // 3) call method via reflection
- Method show = clazz.getDeclaredMethod("show");
- show.invoke(p);
-
- // 4) get class' private structure (attr, method..) via reflection
- Constructor cons1 = clazz.getDeclaredConstructor(String.class);
- cons1.setAccessible(true);
- Person p1 = (Person) cons1.newInstance("trek");
- System.out.println(p1);
-
- // use private attr
- Field name = clazz.getDeclaredField("name");
- name.setAccessible(true);
- name.set(p1, "athena");
- System.out.println(p1);
-
- // use private method
- Method showNation = clazz.getDeclaredMethod("showNation", String.class);
- // compare : p1.showNation("japan"); -> instance call method
- // below is : "Method showNation" call instance -> still instance call method
- showNation.setAccessible(true); // note !!! we need this, so can access private method
- String nation = (String) showNation.invoke(p1, "japan"); // similar as String nation = p1.showNation();
- System.out.println("nation = " + nation);
- }
-
- /**
- * How to get Class instance ?
- *
- * method 1) : Class clazz1 = Person.class;
- * method 2) : via running class instance, via getClass()
- * method 3) : via Class' static method : forName(String classPath) (use most!!)
- * method 4) via "ClassLoader" (rarely use)
- *
- */
- @Test
- public void test3() throws ClassNotFoundException {
-
- // method 1) : via running class attr (xxx.class)
- Class clazz1 = Person.class;
- System.out.println("clazz1 = " + clazz1);
-
- // method 2) : via running class instance, via getClass()
- Person p1 = new Person();
- Class clazz2 = p1.getClass();
- System.out.println("clazz2 = " + clazz2);
-
- // method 3): via Class' static method : forName(String classPath) (use most!!)
- Class clazz3 = Class.forName("Advances.Reflection.Person");
- System.out.println("clazz3 = " + clazz3);
-
- System.out.println("clazz1 == clazz2 ? " + (clazz1 == clazz2) ); // true, NOTE : clazz1, clazz2 are equal
- System.out.println("clazz1 == clazz3 ? " + (clazz1 == clazz3) ); // true, NOTE : clazz1, clazz3 are equal
-
- // method 4) via "ClassLoader" (rarely use)
- ClassLoader classLoader = demo1.class.getClassLoader();
- Class clazz4 = classLoader.loadClass("Advances.Reflection.Person");
- System.out.println("clazz4 = " + clazz4);
-
- System.out.println("clazz1 == clazz4 ? " + (clazz1 == clazz4) ); // true, NOTE : clazz1, clazz4 are equal
- }
-
- /** class instance's structure demo */
- @Test
- public void test4(){
- Class c1 = Object.class;
- Class c2 = Comparable.class;
- Class c3 = String[].class;
- Class c4 = int[][].class;
- Class c5 = ElementType.class;
- Class c6 = Override.class;
- Class c7 = int.class;
- Class c8 = void.class;
- Class c9 = Class.class;
-
- int[] a = new int[10];
- int[] b = new int[100];
- Class c10 = a.getClass();
- Class c11 = b.getClass();
-
- // if array element type, and dimension are the same, they belong to the same class
- System.out.println(c10 == c11); // true
- }
-
+ /** test 1: Before reflection, op we can do on Person class */
+ @Test
+ public void test1() {
+ // 1) create Person class (init)
+ Person p1 = new Person("kate", 17);
+
+ // 2) via instance, use its method
+ p1.age = 20;
+ System.out.println(p1);
+
+ p1.show();
+
+ // can't use Person instance's private method, attr.. outside Person class
+ }
+
+ /** test 2: After reflection, op we can do on Person class */
+ @Test
+ public void test2() throws Exception {
+
+ // 1) create an instance via reflection
+ Class clazz = Person.class;
+ Constructor cons = clazz.getConstructor(String.class, int.class);
+
+ Object obj = cons.newInstance("kate", 17);
+ System.out.println(obj);
+
+ // DownCasting (強轉)
+ Person p = (Person) obj;
+ System.out.println(p);
+
+ // 2) call attr. via reflection
+ Field age = clazz.getDeclaredField("age");
+ age.set(p, 100);
+ System.out.println(p);
+
+ // 3) call method via reflection
+ Method show = clazz.getDeclaredMethod("show");
+ show.invoke(p);
+
+ // 4) get class' private structure (attr, method..) via reflection
+ Constructor cons1 = clazz.getDeclaredConstructor(String.class);
+ cons1.setAccessible(true);
+ Person p1 = (Person) cons1.newInstance("trek");
+ System.out.println(p1);
+
+ // use private attr
+ Field name = clazz.getDeclaredField("name");
+ name.setAccessible(true);
+ name.set(p1, "athena");
+ System.out.println(p1);
+
+ // use private method
+ Method showNation = clazz.getDeclaredMethod("showNation", String.class);
+ // compare : p1.showNation("japan"); -> instance call method
+ // below is : "Method showNation" call instance -> still instance call method
+ showNation.setAccessible(true); // note !!! we need this, so can access private method
+ String nation =
+ (String) showNation.invoke(p1, "japan"); // similar as String nation = p1.showNation();
+ System.out.println("nation = " + nation);
+ }
+
+ /**
+ * How to get Class instance ?
+ *
+ * method 1) : Class clazz1 = Person.class; method 2) : via running class instance, via
+ * getClass() method 3) : via Class' static method : forName(String classPath) (use most!!) method
+ * 4) via "ClassLoader" (rarely use)
+ */
+ @Test
+ public void test3() throws ClassNotFoundException {
+
+ // method 1) : via running class attr (xxx.class)
+ Class clazz1 = Person.class;
+ System.out.println("clazz1 = " + clazz1);
+
+ // method 2) : via running class instance, via getClass()
+ Person p1 = new Person();
+ Class clazz2 = p1.getClass();
+ System.out.println("clazz2 = " + clazz2);
+
+ // method 3): via Class' static method : forName(String classPath) (use most!!)
+ Class clazz3 = Class.forName("Advances.Reflection.Person");
+ System.out.println("clazz3 = " + clazz3);
+
+ System.out.println(
+ "clazz1 == clazz2 ? " + (clazz1 == clazz2)); // true, NOTE : clazz1, clazz2 are equal
+ System.out.println(
+ "clazz1 == clazz3 ? " + (clazz1 == clazz3)); // true, NOTE : clazz1, clazz3 are equal
+
+ // method 4) via "ClassLoader" (rarely use)
+ ClassLoader classLoader = demo1.class.getClassLoader();
+ Class clazz4 = classLoader.loadClass("Advances.Reflection.Person");
+ System.out.println("clazz4 = " + clazz4);
+
+ System.out.println(
+ "clazz1 == clazz4 ? " + (clazz1 == clazz4)); // true, NOTE : clazz1, clazz4 are equal
+ }
+
+ /** class instance's structure demo */
+ @Test
+ public void test4() {
+ Class c1 = Object.class;
+ Class c2 = Comparable.class;
+ Class c3 = String[].class;
+ Class c4 = int[][].class;
+ Class c5 = ElementType.class;
+ Class c6 = Override.class;
+ Class c7 = int.class;
+ Class c8 = void.class;
+ Class c9 = Class.class;
+
+ int[] a = new int[10];
+ int[] b = new int[100];
+ Class c10 = a.getClass();
+ Class c11 = b.getClass();
+
+ // if array element type, and dimension are the same, they belong to the same class
+ System.out.println(c10 == c11); // true
+ }
}
diff --git a/src/main/java/Advances/Reflection/demo3.java b/src/main/java/Advances/Reflection/demo3.java
index 04f7a3f3..fdb3c1aa 100644
--- a/src/main/java/Advances/Reflection/demo3.java
+++ b/src/main/java/Advances/Reflection/demo3.java
@@ -5,48 +5,43 @@
import java.util.Random;
import org.junit.jupiter.api.Test;
-/**
- * Reflection demo3 : reflection dynamic
- *
- */
-
+/** Reflection demo3 : reflection dynamic */
public class demo3 {
- /** create a class instance with classPath (declare class name) */
- public Object getInstance(String classPath) throws Exception {
- Class clazz = Class.forName(classPath);
- return clazz.newInstance();
+ /** create a class instance with classPath (declare class name) */
+ public Object getInstance(String classPath) throws Exception {
+ Class clazz = Class.forName(classPath);
+ return clazz.newInstance();
+ }
+
+ /**
+ * reflection dynamic !!! -> via reflection, We can get class instance dynamically during Runtime
+ * -> used A LOT in backend framework
+ */
+ @Test
+ public void test1() {
+ int num = new Random().nextInt(3);
+ String classPath = "";
+ switch (num) {
+ case 0:
+ classPath = "java.util.Date";
+ break;
+ case 1:
+ // classPath = "java.sql.Date"; // can't use this, since "java.sql.Date" has NO non-param
+ // constructor
+ classPath = "java.lang.Object";
+ break;
+ case 2:
+ classPath = "Advances.Reflection.Person";
+ break;
}
- /**
- * reflection dynamic !!!
- * -> via reflection, We can get class instance dynamically during Runtime
- * -> used A LOT in backend framework
- */
- @Test
- public void test1(){
- int num = new Random().nextInt(3);
- String classPath = "";
- switch (num){
- case 0:
- classPath = "java.util.Date";
- break;
- case 1:
- //classPath = "java.sql.Date"; // can't use this, since "java.sql.Date" has NO non-param constructor
- classPath = "java.lang.Object";
- break;
- case 2:
- classPath = "Advances.Reflection.Person";
- break;
- }
-
- try {
- Object obj = getInstance(classPath);
- System.out.println(">>> obj = " + obj);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
+ try {
+ Object obj = getInstance(classPath);
+ System.out.println(">>> obj = " + obj);
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new RuntimeException(e);
}
-
+ }
}
diff --git a/src/main/java/Advances/Reflection/demo4.java b/src/main/java/Advances/Reflection/demo4.java
index 57a0960c..cf129b6d 100644
--- a/src/main/java/Advances/Reflection/demo4.java
+++ b/src/main/java/Advances/Reflection/demo4.java
@@ -7,70 +7,62 @@
import java.lang.reflect.Modifier;
import org.junit.jupiter.api.Test;
-/**
- * Reflection demo4 : get attr, class name, data type, permission (running class instance)
- *
- */
-
+/** Reflection demo4 : get attr, class name, data type, permission (running class instance) */
public class demo4 {
- /** Field test
- *
- * 1) get all attr (fields) from running class instance
- */
- @Test
- public void test1(){
-
- Class clazz = Advances.Reflection.Person2.class;
-
- /**
- * get attr
- * -> getFields() : get all (public) attr from running class instance
- * -> attr needs to be public (parent attr is NOT included)
- */
- Field[] fields = clazz.getFields();
- for (Field f : fields){
- System.out.println(f);
- }
+ /**
+ * Field test
+ *
+ * 1) get all attr (fields) from running class instance
+ */
+ @Test
+ public void test1() {
- System.out.println("==================");
+ Class clazz = Advances.Reflection.Person2.class;
- /**
- * get attr
- * -> getDeclaredFields() : get all (any permission) attr from running class instance
- * -> attr can be any permission (private, protected, public...)
- */
- Field[] declaredField = clazz.getDeclaredFields();
- for (Field f : declaredField){
- System.out.println(f);
- }
+ /**
+ * get attr -> getFields() : get all (public) attr from running class instance -> attr needs to
+ * be public (parent attr is NOT included)
+ */
+ Field[] fields = clazz.getFields();
+ for (Field f : fields) {
+ System.out.println(f);
}
+ System.out.println("==================");
- /** permission annotation : data type, variable name */
- @Test
- public void test2(){
+ /**
+ * get attr -> getDeclaredFields() : get all (any permission) attr from running class instance
+ * -> attr can be any permission (private, protected, public...)
+ */
+ Field[] declaredField = clazz.getDeclaredFields();
+ for (Field f : declaredField) {
+ System.out.println(f);
+ }
+ }
- Class clazz = Advances.Reflection.Person2.class;
- Field[] declaredField = clazz.getDeclaredFields();
- for (Field f : declaredField){
+ /** permission annotation : data type, variable name */
+ @Test
+ public void test2() {
- // 1) permission annotation
- int modifier = f.getModifiers();
- //System.out.println(modifier); // 0, 1, 2 ...
- System.out.println(Modifier.toString(modifier)); // private, public ...
+ Class clazz = Advances.Reflection.Person2.class;
+ Field[] declaredField = clazz.getDeclaredFields();
+ for (Field f : declaredField) {
- // 2) data type
- Class type = f.getType();
- System.out.println(type.getName());
+ // 1) permission annotation
+ int modifier = f.getModifiers();
+ // System.out.println(modifier); // 0, 1, 2 ...
+ System.out.println(Modifier.toString(modifier)); // private, public ...
- // 3) variable name
- String fName = f.getName();
- System.out.println(fName);
+ // 2) data type
+ Class type = f.getType();
+ System.out.println(type.getName());
- System.out.println("==================");
- }
+ // 3) variable name
+ String fName = f.getName();
+ System.out.println(fName);
+ System.out.println("==================");
}
-
+ }
}
diff --git a/src/main/java/Advances/Reflection/demo5.java b/src/main/java/Advances/Reflection/demo5.java
index 3cb5f499..f53bf9a1 100644
--- a/src/main/java/Advances/Reflection/demo5.java
+++ b/src/main/java/Advances/Reflection/demo5.java
@@ -8,90 +8,84 @@
import java.lang.reflect.Modifier;
import org.junit.jupiter.api.Test;
-/**
- * Reflection demo5 : get method (running class instance)
- *
- */
-
+/** Reflection demo5 : get method (running class instance) */
public class demo5 {
- @Test
- public void test1(){
-
- Class clazz = Person2.class;
+ @Test
+ public void test1() {
- /** getMethods() : get all methods (with public permission) (parent's methods are NOT included) */
- Method[] methods = clazz.getMethods();
- for (Method m : methods){
- System.out.println(m);
- }
+ Class clazz = Person2.class;
- System.out.println("================");
+ /**
+ * getMethods() : get all methods (with public permission) (parent's methods are NOT included)
+ */
+ Method[] methods = clazz.getMethods();
+ for (Method m : methods) {
+ System.out.println(m);
+ }
- /** getDeclaredMethods() : get all declared methods in running class instance*/
- Method[] declaredMethods = clazz.getDeclaredMethods();
- for (Method m : declaredMethods){
- System.out.println(m);
- }
+ System.out.println("================");
- // there are similar methods for getting constructor...
+ /** getDeclaredMethods() : get all declared methods in running class instance */
+ Method[] declaredMethods = clazz.getDeclaredMethods();
+ for (Method m : declaredMethods) {
+ System.out.println(m);
}
- /**
- * How can we get "@XXXyyy" ?
- *
- * @XXXyyy
- * permission-annotation return-type method-name(type1 arg1 ...) throws xxxException(..){}
- *
- * 1) @XXXyyy has to be with RUNTIME life-cycle (so we can get it via reflection)
- *
- */
- @Test
- public void test2(){
-
- Class clazz = Person2.class;
- Method[] declaredMethods = clazz.getDeclaredMethods();
- for (Method m : declaredMethods){
-
- // 1) get method declared annotation
- Annotation[] annos = m.getAnnotations();
- for (Annotation a: annos){
- System.out.println(">>> method = " + a);
- }
-
- // 2) get permission annotation
- System.out.println(">>> permission" + Modifier.toString(m.getModifiers()));
-
- // 3) get method return type
- System.out.println(">>> return type = " + m.getReturnType().getName());
-
- // 4) get method name
- System.out.println(">>> method = " + m.getName());
-
- // 5) get param list
- Class[] parameterTypes = m.getParameterTypes();
- // if there is param list
- if ( !(parameterTypes == null && parameterTypes.length == 0) ){
- for (int i = 0; i < parameterTypes.length; i++){
- System.out.println(">>> parameterTypes = " + parameterTypes[i].getName()+ " args_" + i);
- }
- }
-
- // 6) get throw exceptions
- Class[] exceptionTypes = m.getExceptionTypes();
- if ( !(exceptionTypes == null && exceptionTypes.length == 0) ){
- System.out.println(">>> throws " );
- for (int i = 0; i < exceptionTypes.length; i++){
- if (i == exceptionTypes.length - 1){
- System.out.println(exceptionTypes[i].getName());
- break;
- }
- System.out.println(exceptionTypes[i].getName() + ",");
- }
- }
-
- System.out.println("================");
+ // there are similar methods for getting constructor...
+ }
+
+ /**
+ * How can we get "@XXXyyy" ? @XXXyyy permission-annotation return-type method-name(type1 arg1
+ * ...) throws xxxException(..){}
+ *
+ *
1) @XXXyyy has to be with RUNTIME life-cycle (so we can get it via reflection)
+ */
+ @Test
+ public void test2() {
+
+ Class clazz = Person2.class;
+ Method[] declaredMethods = clazz.getDeclaredMethods();
+ for (Method m : declaredMethods) {
+
+ // 1) get method declared annotation
+ Annotation[] annos = m.getAnnotations();
+ for (Annotation a : annos) {
+ System.out.println(">>> method = " + a);
+ }
+
+ // 2) get permission annotation
+ System.out.println(">>> permission" + Modifier.toString(m.getModifiers()));
+
+ // 3) get method return type
+ System.out.println(">>> return type = " + m.getReturnType().getName());
+
+ // 4) get method name
+ System.out.println(">>> method = " + m.getName());
+
+ // 5) get param list
+ Class[] parameterTypes = m.getParameterTypes();
+ // if there is param list
+ if (!(parameterTypes == null && parameterTypes.length == 0)) {
+ for (int i = 0; i < parameterTypes.length; i++) {
+ System.out.println(">>> parameterTypes = " + parameterTypes[i].getName() + " args_" + i);
}
- }
+ }
+
+ // 6) get throw exceptions
+ Class[] exceptionTypes = m.getExceptionTypes();
+ if (!(exceptionTypes == null && exceptionTypes.length == 0)) {
+ System.out.println(">>> throws ");
+ for (int i = 0; i < exceptionTypes.length; i++) {
+ if (i == exceptionTypes.length - 1) {
+ System.out.println(exceptionTypes[i].getName());
+ break;
+ }
+ System.out.println(exceptionTypes[i].getName() + ",");
+ }
+ }
+ System.out.println("================");
+ }
+ }
}
diff --git a/src/main/java/Advances/Reflection/demo6.java b/src/main/java/Advances/Reflection/demo6.java
index 7d50ce43..7db510f5 100644
--- a/src/main/java/Advances/Reflection/demo6.java
+++ b/src/main/java/Advances/Reflection/demo6.java
@@ -3,10 +3,10 @@
// https://www.youtube.com/watch?v=A4oHXSAlmFg&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=652
// https://www.youtube.com/watch?v=1cZzR0lmaPo&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=652
-import org.junit.jupiter.api.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
+import org.junit.jupiter.api.Test;
public class demo6 {
diff --git a/src/main/java/Advances/Reflection/demo7.java b/src/main/java/Advances/Reflection/demo7.java
index 9786f8a7..67fa8f4d 100644
--- a/src/main/java/Advances/Reflection/demo7.java
+++ b/src/main/java/Advances/Reflection/demo7.java
@@ -2,8 +2,8 @@
// https://www.youtube.com/watch?v=HSDlxdr7bXw&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=654
-import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation;
+import org.junit.jupiter.api.Test;
public class demo7 {
diff --git a/src/main/java/Advances/Reflection/demo8.java b/src/main/java/Advances/Reflection/demo8.java
index 70b086f5..37bf2391 100644
--- a/src/main/java/Advances/Reflection/demo8.java
+++ b/src/main/java/Advances/Reflection/demo8.java
@@ -5,62 +5,59 @@
import java.lang.reflect.Field;
import org.junit.jupiter.api.Test;
-/** get specific structure from running class
+/**
+ * get specific structure from running class
*
- * -> e.g. attribute, method, constructor
+ *
-> e.g. attribute, method, constructor
*/
-
public class demo8 {
- /**
- * get fields : V1
- */
- @Test
- public void test1() throws Exception {
-
- Class clazz = Person2.class;
+ /** get fields : V1 */
+ @Test
+ public void test1() throws Exception {
- // get running class instance
- Person2 p = (Person2) clazz.newInstance();
+ Class clazz = Person2.class;
- // get defined attr (attr has to be "public")
- // (we seldom use this approach, plz check test2 for better one)
- Field id = clazz.getField("id");
+ // get running class instance
+ Person2 p = (Person2) clazz.newInstance();
- // set current attr value.
- // pattern : set(instanceName, attrVal)
- id.set(p, 1009);
+ // get defined attr (attr has to be "public")
+ // (we seldom use this approach, plz check test2 for better one)
+ Field id = clazz.getField("id");
- // get current class instance attr val
- // pattern : get(instanceName)
- int pid = (int) id.get(p);
- System.out.println(">>> pid = " + pid);
- }
+ // set current attr value.
+ // pattern : set(instanceName, attrVal)
+ id.set(p, 1009);
- /**
- * get fields : V2
- *
- * set, get running class instance attr
- */
- @Test
- public void test2() throws Exception {
+ // get current class instance attr val
+ // pattern : get(instanceName)
+ int pid = (int) id.get(p);
+ System.out.println(">>> pid = " + pid);
+ }
- Class clazz = Person2.class;
+ /**
+ * get fields : V2
+ *
+ *
set, get running class instance attr
+ */
+ @Test
+ public void test2() throws Exception {
- // get running class instance
- Person2 p = (Person2) clazz.newInstance();
+ Class clazz = Person2.class;
- // get defined attr (attr don's have to be "public")
- // pattern : getDeclaredField(String fieldName)
- Field name = clazz.getDeclaredField("name");
+ // get running class instance
+ Person2 p = (Person2) clazz.newInstance();
- // MAKE sure attr is accessible
- // NOTE !!! we HAVE to make setAccessible true, so we can set val to attr
- name.setAccessible(true);
+ // get defined attr (attr don's have to be "public")
+ // pattern : getDeclaredField(String fieldName)
+ Field name = clazz.getDeclaredField("name");
- // set attr val
- name.set(p, "jack");
- System.out.println(name.get(p));
- }
+ // MAKE sure attr is accessible
+ // NOTE !!! we HAVE to make setAccessible true, so we can set val to attr
+ name.setAccessible(true);
+ // set attr val
+ name.set(p, "jack");
+ System.out.println(name.get(p));
+ }
}
diff --git a/src/main/java/Advances/Reflection/demo9.java b/src/main/java/Advances/Reflection/demo9.java
index 30961534..b830463e 100644
--- a/src/main/java/Advances/Reflection/demo9.java
+++ b/src/main/java/Advances/Reflection/demo9.java
@@ -9,55 +9,53 @@
public class demo9 {
- /** Get methods from running class instance (Important!!) */
- @Test
- public void test1() throws Exception {
+ /** Get methods from running class instance (Important!!) */
+ @Test
+ public void test1() throws Exception {
- Class clazz = Person2.class;
+ Class clazz = Person2.class;
- // get running class instance
- Person2 p = (Person2) clazz.newInstance();
+ // get running class instance
+ Person2 p = (Person2) clazz.newInstance();
- // step 1) get specific method
- // pattern : getDeclaredMethod(methodName, return-type)
- Method show = clazz.getDeclaredMethod("show", String.class);
+ // step 1) get specific method
+ // pattern : getDeclaredMethod(methodName, return-type)
+ Method show = clazz.getDeclaredMethod("show", String.class);
- // step 2) make sure method is accessible
- show.setAccessible(true);
+ // step 2) make sure method is accessible
+ show.setAccessible(true);
- // step 3) invoke : call method
- // pattern : invoke(method-class, attr-val)
- // invoke method has return value
- Object res = show.invoke(p, "JPY");
- System.out.println(">>> res = " + res);
+ // step 3) invoke : call method
+ // pattern : invoke(method-class, attr-val)
+ // invoke method has return value
+ Object res = show.invoke(p, "JPY");
+ System.out.println(">>> res = " + res);
- System.out.println("====== How to call static method ? =====");
+ System.out.println("====== How to call static method ? =====");
- Method showDest = clazz.getDeclaredMethod("showDest");
- // make sure accessible
- showDest.setAccessible(true);
- // if there is no return val, res will be null
- Object res2 = showDest.invoke(Person2.class);
- System.out.println(">>> res2 = " + res2);
- }
+ Method showDest = clazz.getDeclaredMethod("showDest");
+ // make sure accessible
+ showDest.setAccessible(true);
+ // if there is no return val, res will be null
+ Object res2 = showDest.invoke(Person2.class);
+ System.out.println(">>> res2 = " + res2);
+ }
- /** call running class defined constructor */
- @Test
- public void test2() throws Exception {
+ /** call running class defined constructor */
+ @Test
+ public void test2() throws Exception {
- Class clazz = Person2.class;
+ Class clazz = Person2.class;
- // 1) get constructor
- // pattern : clazz.getDeclaredConstructor(class-type)
- Constructor constructor = clazz.getDeclaredConstructor(String.class);
+ // 1) get constructor
+ // pattern : clazz.getDeclaredConstructor(class-type)
+ Constructor constructor = clazz.getDeclaredConstructor(String.class);
- // 2) make sure accessible
- constructor.setAccessible(true);
-
- // 3) create running class instance
- Person2 p2 = (Person2) constructor.newInstance("jack");
- System.out.println(">>> p2 = " + p2);
-
- }
+ // 2) make sure accessible
+ constructor.setAccessible(true);
+ // 3) create running class instance
+ Person2 p2 = (Person2) constructor.newInstance("jack");
+ System.out.println(">>> p2 = " + p2);
+ }
}
diff --git a/src/main/java/Advances/StreamAPI/demo1.java b/src/main/java/Advances/StreamAPI/demo1.java
index 0ce3c7e3..ce4c1fee 100644
--- a/src/main/java/Advances/StreamAPI/demo1.java
+++ b/src/main/java/Advances/StreamAPI/demo1.java
@@ -5,13 +5,11 @@
import Advances.Lambda.demo4.Employee;
import Advances.Lambda.demo4.EmployeeData;
-
-import org.junit.jupiter.api.Test;
-
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
+import org.junit.jupiter.api.Test;
/**
* Stream API demo 1
diff --git a/src/main/java/Advances/StreamAPI/demo2.java b/src/main/java/Advances/StreamAPI/demo2.java
index 6142b0d4..18fea88f 100644
--- a/src/main/java/Advances/StreamAPI/demo2.java
+++ b/src/main/java/Advances/StreamAPI/demo2.java
@@ -13,195 +13,183 @@
import org.junit.jupiter.api.Test;
/**
- * Stream API demo 2
+ * Stream API demo 2
*
- * Stream intermedia op
+ *
Stream intermedia op
*
- * 1) filter, sampling
- * 2) mapping
- * 3) ordering
+ *
1) filter, sampling 2) mapping 3) ordering
*/
-
public class demo2 {
- /** transform char in string to stream */
- public static Stream fromStringToStream(String str){
-
- ArrayList list = new ArrayList<>();
- for(Character c : str.toCharArray()){
- list.add(c);
- }
- return list.stream();
- }
-
- /**
- * demo 1 :
- * -> filter(Predicate p) : accept Lambda, filter elements from stream
- * -> limit(n) : only get element with limit count
- * -> skip(n) : neglect elements : return a stream neglect first n elements
- * -> distinct : via hashCode(), and equals() de-duplicate elements and return
- */
- @Test
- public void test1(){
-
- // init
- List list = EmployeeData.getEmployees();
- Stream stream = list.stream();
-
- // filter
- stream.filter(e -> e.getSalary() > 100)
- .forEach(System.out::println);
-
- System.out.println("================");
-
- // limit
- // below is wrong, CAN'T do limit op on already closed stream (java.lang.IllegalStateException: stream has already been operated upon or closed)
- //stream.limit(2).forEach(System.out::println);
- list.stream().limit(2).forEach(System.out::println);
-
- System.out.println("================");
-
- // skip
- // below is wrong, CAN'T do limit op on already closed stream (java.lang.IllegalStateException: stream has already been operated upon or closed)
- // stream.skip(2).forEach(System.out::println);
- list.stream().skip(3).forEach(System.out::println);
-
- System.out.println("================");
-
- // distinct
- // add duplicated data
- list.add(new Employee(1001, "jack", 34, 700.1));
- list.add(new Employee(1001, "jack", 34, 700.1));
- list.add(new Employee(1001, "jack", 34, 700.1));
- list.add(new Employee(1001, "jack", 34, 700.1));
-
- list.stream().distinct().forEach(System.out::println);
- }
-
- /**
- * demo 2
- * -> map(Function f) : receive a func as param,
- * transform elements with it
- *
- * -> flatMap(Function f) : receive a func as param,
- * transform elements with it
- * if there are sub-streams
- * will put all of them into original stream ("flat")
- */
- @Test
- public void test2(){
-
- // init
- List list = Arrays.asList("AA", "aa", "bb","cc", "dd");
- Stream stream = list.stream();
-
- List employees = EmployeeData.getEmployees();
-
- // map demo 1
- stream.map(str -> str.toUpperCase()).forEach(System.out::println);
-
- System.out.println("================");
-
- // map demo 2 : filter age > 3
- //employees.stream().map(str -> str.getAge() > 3).map(Employee::getName);
- Stream namesStream = employees.stream().map(Employee::getName);
- namesStream.filter(name -> name.length() > 3).forEach(System.out::println);
+ /** transform char in string to stream */
+ public static Stream fromStringToStream(String str) {
- System.out.println("================");
-
- // flatMap demo 1
- // if still use map (not use flatMap)
- Stream> streamStream = list.stream().map(demo2::fromStringToStream);
- streamStream.forEach(System.out::println);
-
- System.out.println("================");
-
- Stream characterStream = list.stream().flatMap(demo2::fromStringToStream);
- characterStream.forEach(System.out::println);
+ ArrayList list = new ArrayList<>();
+ for (Character c : str.toCharArray()) {
+ list.add(c);
}
+ return list.stream();
+ }
- /**
- * Review :
- * -> list.add() VS list.addAll()
- * -> similar as map VS flatMap
- */
- @Test
- public void test3(){
-
- ArrayList list1 = new ArrayList<>();
- list1.add(1);
- list1.add(2);
- list1.add(3);
-
- ArrayList list1_ = new ArrayList<>();
- list1_.add(1);
- list1_.add(2);
- list1_.add(3);
-
- ArrayList list2 = new ArrayList<>();
- list2.add(4);
- list2.add(5);
- list2.add(6);
-
- list1.add(list2);
- System.out.println("list1 = " + list1);
-
- list1_.addAll(list2);
- System.out.println("list1_ = " + list1_);
- }
-
- /**
- * Sorting
- * 1) sorted() : natural ordering, generate a new stream, order by natural ordering
- * 2) sorted(Comparator com) : custom ordering, generate a new stream, order by Comparator ordering
- */
- @Test
- public void test4(){
-
- // init
- List list = Arrays.asList(12,-9,0,100,200,1000);
- Stream stream = list.stream();
-
- // sorted() demo 1
- list.stream().sorted().forEach(System.out::println);
-
- System.out.println("================");
-
- // sorted() demo 2
- List employees = EmployeeData.getEmployees();
- // wrong, error : java.lang.ClassCastException: Advances.Lambda.demo4.Employee cannot be cast to java.lang.Comparable
- // since employees has NO implementation on Comparator interface
- // employees.stream().sorted().forEach(System.out::println);
-
- System.out.println("================");
-
- // sorted(Comparator com) demo 1
- List employees2 = EmployeeData.getEmployees();
- employees2.stream().sorted(
- // implement Comparator with lambda expression
- (e1, e2) -> {
- return Integer.compare(e1.getAge(), e2.getAge());
- }
- ).forEach(System.out::println);
-
- System.out.println("================");
-
- // sorted(Comparator com) demo 2
- List employees3 = EmployeeData.getEmployees();
- employees2.stream().sorted(
- // implement Comparator with lambda expression
- (e1, e2) -> {
- // if age are different, return result directly
- int ageVal = Integer.compare(e1.getAge(), e2.getAge());
- if (ageVal != 0){
- return ageVal;
- }else{
- // if age are the same, compare salary instead
- return Double.compare(e1.getSalary(), e2.getSalary());
- }
- }
- ).forEach(System.out::println);
+ /**
+ * demo 1 : -> filter(Predicate p) : accept Lambda, filter elements from stream -> limit(n) : only
+ * get element with limit count -> skip(n) : neglect elements : return a stream neglect first n
+ * elements -> distinct : via hashCode(), and equals() de-duplicate elements and return
+ */
+ @Test
+ public void test1() {
- }
+ // init
+ List list = EmployeeData.getEmployees();
+ Stream stream = list.stream();
+
+ // filter
+ stream.filter(e -> e.getSalary() > 100).forEach(System.out::println);
+
+ System.out.println("================");
+
+ // limit
+ // below is wrong, CAN'T do limit op on already closed stream (java.lang.IllegalStateException:
+ // stream has already been operated upon or closed)
+ // stream.limit(2).forEach(System.out::println);
+ list.stream().limit(2).forEach(System.out::println);
+ System.out.println("================");
+
+ // skip
+ // below is wrong, CAN'T do limit op on already closed stream (java.lang.IllegalStateException:
+ // stream has already been operated upon or closed)
+ // stream.skip(2).forEach(System.out::println);
+ list.stream().skip(3).forEach(System.out::println);
+
+ System.out.println("================");
+
+ // distinct
+ // add duplicated data
+ list.add(new Employee(1001, "jack", 34, 700.1));
+ list.add(new Employee(1001, "jack", 34, 700.1));
+ list.add(new Employee(1001, "jack", 34, 700.1));
+ list.add(new Employee(1001, "jack", 34, 700.1));
+
+ list.stream().distinct().forEach(System.out::println);
+ }
+
+ /**
+ * demo 2 -> map(Function f) : receive a func as param, transform elements with it
+ *
+ * -> flatMap(Function f) : receive a func as param, transform elements with it if there are
+ * sub-streams will put all of them into original stream ("flat")
+ */
+ @Test
+ public void test2() {
+
+ // init
+ List list = Arrays.asList("AA", "aa", "bb", "cc", "dd");
+ Stream stream = list.stream();
+
+ List employees = EmployeeData.getEmployees();
+
+ // map demo 1
+ stream.map(str -> str.toUpperCase()).forEach(System.out::println);
+
+ System.out.println("================");
+
+ // map demo 2 : filter age > 3
+ // employees.stream().map(str -> str.getAge() > 3).map(Employee::getName);
+ Stream namesStream = employees.stream().map(Employee::getName);
+ namesStream.filter(name -> name.length() > 3).forEach(System.out::println);
+
+ System.out.println("================");
+
+ // flatMap demo 1
+ // if still use map (not use flatMap)
+ Stream> streamStream = list.stream().map(demo2::fromStringToStream);
+ streamStream.forEach(System.out::println);
+
+ System.out.println("================");
+
+ Stream characterStream = list.stream().flatMap(demo2::fromStringToStream);
+ characterStream.forEach(System.out::println);
+ }
+
+ /** Review : -> list.add() VS list.addAll() -> similar as map VS flatMap */
+ @Test
+ public void test3() {
+
+ ArrayList list1 = new ArrayList<>();
+ list1.add(1);
+ list1.add(2);
+ list1.add(3);
+
+ ArrayList list1_ = new ArrayList<>();
+ list1_.add(1);
+ list1_.add(2);
+ list1_.add(3);
+
+ ArrayList list2 = new ArrayList<>();
+ list2.add(4);
+ list2.add(5);
+ list2.add(6);
+
+ list1.add(list2);
+ System.out.println("list1 = " + list1);
+
+ list1_.addAll(list2);
+ System.out.println("list1_ = " + list1_);
+ }
+
+ /**
+ * Sorting 1) sorted() : natural ordering, generate a new stream, order by natural ordering 2)
+ * sorted(Comparator com) : custom ordering, generate a new stream, order by Comparator ordering
+ */
+ @Test
+ public void test4() {
+
+ // init
+ List list = Arrays.asList(12, -9, 0, 100, 200, 1000);
+ Stream stream = list.stream();
+
+ // sorted() demo 1
+ list.stream().sorted().forEach(System.out::println);
+
+ System.out.println("================");
+
+ // sorted() demo 2
+ List employees = EmployeeData.getEmployees();
+ // wrong, error : java.lang.ClassCastException: Advances.Lambda.demo4.Employee cannot be cast to
+ // java.lang.Comparable
+ // since employees has NO implementation on Comparator interface
+ // employees.stream().sorted().forEach(System.out::println);
+
+ System.out.println("================");
+
+ // sorted(Comparator com) demo 1
+ List employees2 = EmployeeData.getEmployees();
+ employees2.stream()
+ .sorted(
+ // implement Comparator with lambda expression
+ (e1, e2) -> {
+ return Integer.compare(e1.getAge(), e2.getAge());
+ })
+ .forEach(System.out::println);
+
+ System.out.println("================");
+
+ // sorted(Comparator com) demo 2
+ List employees3 = EmployeeData.getEmployees();
+ employees2.stream()
+ .sorted(
+ // implement Comparator with lambda expression
+ (e1, e2) -> {
+ // if age are different, return result directly
+ int ageVal = Integer.compare(e1.getAge(), e2.getAge());
+ if (ageVal != 0) {
+ return ageVal;
+ } else {
+ // if age are the same, compare salary instead
+ return Double.compare(e1.getSalary(), e2.getSalary());
+ }
+ })
+ .forEach(System.out::println);
+ }
}
diff --git a/src/main/java/Advances/StreamAPI/demo3.java b/src/main/java/Advances/StreamAPI/demo3.java
index 9cb0efa9..7e17798d 100644
--- a/src/main/java/Advances/StreamAPI/demo3.java
+++ b/src/main/java/Advances/StreamAPI/demo3.java
@@ -5,14 +5,12 @@
import Advances.Lambda.demo4.Employee;
import Advances.Lambda.demo4.EmployeeData;
-
-import org.junit.jupiter.api.Test;
-
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
+import org.junit.jupiter.api.Test;
/**
* Stream API demo 3
diff --git a/src/main/java/Advances/StreamAPI/demo4.java b/src/main/java/Advances/StreamAPI/demo4.java
index 074f73e2..47c77734 100644
--- a/src/main/java/Advances/StreamAPI/demo4.java
+++ b/src/main/java/Advances/StreamAPI/demo4.java
@@ -11,54 +11,56 @@
import org.junit.jupiter.api.Test;
/**
- * Stream API demo 4
+ * Stream API demo 4
*
- * Stream reduce op
+ * Stream reduce op
*
- * 1) reduce(T identity, BinaryOperator) : can aggregate all elements from stream and return final result
+ *
1) reduce(T identity, BinaryOperator) : can aggregate all elements from stream and return
+ * final result
*
- * 2) reduce(BinaryOperator) : can aggregate all elements from stream and return Option as final result
+ * 2) reduce(BinaryOperator) : can aggregate all elements from stream and return Option as
+ * final result
*/
-
public class demo4 {
- @Test
- public void test1(){
-
- /** 1) reduce(T identity, BinaryOperator)
- *
- * -> get sum from 1 - 10
- */
- // init
- List list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
+ @Test
+ public void test1() {
- // style 1
- int res1 = list.stream().reduce(0, (a,b) -> Integer.sum(a,b));
+ /**
+ * 1) reduce(T identity, BinaryOperator)
+ *
+ * -> get sum from 1 - 10
+ */
+ // init
+ List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
- // style 2
- int res2 = list.stream().reduce(0, Integer::sum);
- System.out.println(">>> res1 = " + res1);
- System.out.println(">>> res2 = " + res2);
+ // style 1
+ int res1 = list.stream().reduce(0, (a, b) -> Integer.sum(a, b));
- System.out.println("=================");
+ // style 2
+ int res2 = list.stream().reduce(0, Integer::sum);
+ System.out.println(">>> res1 = " + res1);
+ System.out.println(">>> res2 = " + res2);
- /** 2) reduce(BinaryOperator)
- *
- * -> get sum of employees salary
- */
- // init
- List employees = EmployeeData.getEmployees();
- Stream salaryStream = employees.stream().map(Employee::getSalary);
+ System.out.println("=================");
- // style 1
- //Optional res3 = salaryStream.reduce((a,b) -> Double.sum(a,b));
- Optional res3 = salaryStream.reduce((a,b) -> a+b);
- System.out.println(">>> res3 = " + res3);
+ /**
+ * 2) reduce(BinaryOperator)
+ *
+ * -> get sum of employees salary
+ */
+ // init
+ List employees = EmployeeData.getEmployees();
+ Stream salaryStream = employees.stream().map(Employee::getSalary);
- // style 2
- Stream salaryStream2 = employees.stream().map(Employee::getSalary);
- Optional res4 = salaryStream2.reduce(Double::sum);
- System.out.println(">>> res4 = " + res4);
- }
+ // style 1
+ // Optional res3 = salaryStream.reduce((a,b) -> Double.sum(a,b));
+ Optional res3 = salaryStream.reduce((a, b) -> a + b);
+ System.out.println(">>> res3 = " + res3);
+ // style 2
+ Stream salaryStream2 = employees.stream().map(Employee::getSalary);
+ Optional res4 = salaryStream2.reduce(Double::sum);
+ System.out.println(">>> res4 = " + res4);
+ }
}
diff --git a/src/main/java/Advances/StringBufferStringBuilder1/demo1.java b/src/main/java/Advances/StringBufferStringBuilder1/demo1.java
index 99e427f3..5e7d974e 100644
--- a/src/main/java/Advances/StringBufferStringBuilder1/demo1.java
+++ b/src/main/java/Advances/StringBufferStringBuilder1/demo1.java
@@ -63,7 +63,7 @@ public void test1() {
// common methods in SpringBuffer / SpringBuilder
@Test
public void test2() {
- StringBuffer s1 = new StringBuffer("");
+ StringBuffer s1 = new StringBuffer();
StringBuffer s2 = new StringBuffer("abcde");
// append
diff --git a/src/main/java/Advances/StringClass/demo2.java b/src/main/java/Advances/StringClass/demo2.java
index 5573990e..4c7a0637 100644
--- a/src/main/java/Advances/StringClass/demo2.java
+++ b/src/main/java/Advances/StringClass/demo2.java
@@ -31,8 +31,8 @@ public void test1() {
// method 2) via new + constructor:
// s3, s3 are defined in address in java's stack space
- String s3 = new String("scala");
- String s4 = new String("scala");
+ String s3 = "scala";
+ String s4 = "scala";
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
@@ -68,9 +68,8 @@ public void test2() {
String s3 = "javahadoop"; // literal value
String s4 = "java" + "hadoop"; // concatenation of 2 literal values is still literal value
String s5 =
- s1
- + "hadoop"; // NOTE*** : if there is a variable (e.g. s1) then this value is storage in
- // stack space, but not constant pool space
+ s1 + "hadoop"; // NOTE*** : if there is a variable (e.g. s1) then this value is storage in
+ // stack space, but not constant pool space
String s6 = "java" + s2;
String s7 = s1 + s2;
@@ -90,11 +89,11 @@ public void test2() {
@Test
public void test3() {
// equals `this.value = new char[0];`
- String s1_ = new String();
+ String s1_ = "";
// this.value = original.value;
String str = "helo";
- String s2_ = new String(str); // (String str);
+ String s2_ = str; // (String str);
// this.value = Arrays.copyOf(value, value.length);
// String s3 = new String(char[] a);
diff --git a/src/main/java/Advances/StringMethod/demo2.java b/src/main/java/Advances/StringMethod/demo2.java
index 1c3f966d..80a2ddeb 100644
--- a/src/main/java/Advances/StringMethod/demo2.java
+++ b/src/main/java/Advances/StringMethod/demo2.java
@@ -23,7 +23,7 @@ public void test1() {
System.out.println("================");
- System.out.println(str1.startsWith("h", 0));
+ System.out.println(str1.startsWith("h"));
System.out.println(str1.startsWith("h", 1));
System.out.println("================");
@@ -39,7 +39,7 @@ public void test1() {
System.out.println("================");
- System.out.println(str1.indexOf("ll", 0)); // 2
+ System.out.println(str1.indexOf("ll")); // 2
System.out.println(str1.indexOf("ll", 3)); // -1
System.out.println("================");
diff --git a/src/main/java/Advances/StringTransform/demo1.java b/src/main/java/Advances/StringTransform/demo1.java
index 41030648..c68df983 100644
--- a/src/main/java/Advances/StringTransform/demo1.java
+++ b/src/main/java/Advances/StringTransform/demo1.java
@@ -5,92 +5,87 @@
// https://www.youtube.com/watch?v=c4RArt8F2KY&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=461
/**
- * String class <---> other class Demo 1
+ * String class <---> other class Demo 1
*
- * 1) String <--> Integer
- * 2) String <--> char[]
- * 3) String <--> byte[]
+ * 1) String <--> Integer 2) String <--> char[] 3) String <--> byte[]
*/
-
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
public class demo1 {
- /**
- * String <--> Integer:
- *
- * 1) String -> basic data type, wrapper class (static method): parseXXX(str)
- * 2) basic data type, wrapper class -> String : String override valueOf(xxx)
- */
- @Test
- public void test1(){
- String str1 = "123";
- //int num = (int) str1; // wrong
- int num1 = Integer.parseInt(str1);
- System.out.println(num1);
-
- System.out.println("================");
-
- String str1_ = String.valueOf(num1);
- System.out.println(str1_);
+ /**
+ * String <--> Integer:
+ *
+ *
1) String -> basic data type, wrapper class (static method): parseXXX(str) 2) basic data
+ * type, wrapper class -> String : String override valueOf(xxx)
+ */
+ @Test
+ public void test1() {
+ String str1 = "123";
+ // int num = (int) str1; // wrong
+ int num1 = Integer.parseInt(str1);
+ System.out.println(num1);
+
+ System.out.println("================");
+
+ String str1_ = String.valueOf(num1);
+ System.out.println(str1_);
+ }
+
+ /**
+ * String <---> char[]
+ *
+ *
1) String --> char[] : String's toCharArray method 2) char[] --> String : via String's
+ * constructor
+ */
+ @Test
+ public void test2() {
+ String s1 = "abc123";
+ char[] charArray1 = s1.toCharArray();
+ for (int i = 0; i < charArray1.length; i++) {
+ System.out.println(charArray1[i]);
}
- /**
- * String <---> char[]
- *
- * 1) String --> char[] : String's toCharArray method
- * 2) char[] --> String : via String's constructor
- */
- @Test
- public void test2(){
- String s1 = "abc123";
- char[] charArray1 = s1.toCharArray();
- for (int i=0; i < charArray1.length; i++){
- System.out.println(charArray1[i]);
- }
-
- System.out.println("================");
-
- char[] arr2 = new char[]{'x','y','z'};
- String s2 = new String(arr2);
- System.out.println(s2);
- }
+ System.out.println("================");
- /**
- * String <--> byte[]
- * 1) String -> byte[] : via String's getBytes() method
- *
- * note:
- * String --encode--> byte (binary code)
- * byte --decode--> String
- */
- @Test
- public void test3() throws UnsupportedEncodingException {
- String str1 = "xyz123世界";
- byte[] bytes_1 = str1.getBytes(); // use default encode (e.g. utf-8)
+ char[] arr2 = new char[] {'x', 'y', 'z'};
+ String s2 = new String(arr2);
+ System.out.println(s2);
+ }
- System.out.println(bytes_1);
- System.out.println(Arrays.toString(bytes_1)); // [120, 121, 122, 49, 50, 51, -28, -72, -106, -25, -107, -116]
+ /**
+ * String <--> byte[] 1) String -> byte[] : via String's getBytes() method
+ *
+ *
note: String --encode--> byte (binary code) byte --decode--> String
+ */
+ @Test
+ public void test3() throws UnsupportedEncodingException {
+ String str1 = "xyz123世界";
+ byte[] bytes_1 = str1.getBytes(); // use default encode (e.g. utf-8)
- System.out.println("================");
+ System.out.println(bytes_1);
+ System.out.println(
+ Arrays.toString(bytes_1)); // [120, 121, 122, 49, 50, 51, -28, -72, -106, -25, -107, -116]
- byte[] bytes_2 = str1.getBytes("gbk"); // use gbk encode
+ System.out.println("================");
- System.out.println(bytes_2);
- System.out.println(Arrays.toString(bytes_2)); // [120, 121, 122, 49, 50, 51, -54, -64, -67, -25]
+ byte[] bytes_2 = str1.getBytes("gbk"); // use gbk encode
- System.out.println("================");
+ System.out.println(bytes_2);
+ System.out.println(Arrays.toString(bytes_2)); // [120, 121, 122, 49, 50, 51, -54, -64, -67, -25]
- String str2 = new String(bytes_1);
- System.out.println(str2); // xyz123世界
+ System.out.println("================");
- // if encode with "gbk", then we also need to decode with "gbk", or decode can't work properly
- String str2_ = new String(bytes_2);
- System.out.println(str2_); // xyz123����
+ String str2 = new String(bytes_1);
+ System.out.println(str2); // xyz123世界
- String str3_ = new String(bytes_2,"gbk");
- System.out.println(str3_); // xyz123世界
- }
+ // if encode with "gbk", then we also need to decode with "gbk", or decode can't work properly
+ String str2_ = new String(bytes_2);
+ System.out.println(str2_); // xyz123����
+
+ String str3_ = new String(bytes_2, "gbk");
+ System.out.println(str3_); // xyz123世界
+ }
}
diff --git a/src/main/java/Advances/SystemGetPropertiesDemo1.java b/src/main/java/Advances/SystemGetPropertiesDemo1.java
index 33042c19..286ff113 100644
--- a/src/main/java/Advances/SystemGetPropertiesDemo1.java
+++ b/src/main/java/Advances/SystemGetPropertiesDemo1.java
@@ -5,10 +5,8 @@
/** System getProperties demo 1 */
public class SystemGetPropertiesDemo1 {
public static void main(String[] args) {
- System.out.println(
- System
- .getProperties()); // {java.runtime.name=OpenJDK Runtime Environment,
- // sun.boot.library.path=/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib, java.vm.version=25.292-b10, gopherProxySet=false, java.vm.vendor=BellSoft, java.vendor.url=https://bell-sw.com/, path.separator=:, java.vm.name=OpenJDK 64-Bit Server VM, file.encoding.pkg=sun.io, user.country=TW, sun.java.launcher=SUN_STANDARD, sun.os.patch.level=unknown, java.vm.specification.name=Java Virtual Machine Specification, user.dir=/Users/yennanliu/JavaHelloWorld, java.runtime.version=1.8.0_292-b10, java.awt.graphicsenv=sun.awt.CGraphicsEnvironment, java.endorsed.dirs=/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/endorsed, os.arch=aarch64, java.io.tmpdir=/var/folders/tz/5r4lbzxj5hs5q87gwdwyjnph0000gn/T/, line.separator= java.vm.specification.vendor=Oracle Corporation, os.name=Mac OS X, sun.jnu.encoding=UTF-8, java.library.path=/Users/yennanliu/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:., java.specification.name=Java Platform API Specification, java.class.version=52.0, sun.management.compiler=HotSpot 64-Bit Tiered Compilers, os.version=11.6, http.nonProxyHosts=local|*.local|169.254/16|*.169.254/16, user.home=/Users/yennanliu, user.timezone=, java.awt.printerjob=sun.lwawt.macosx.CPrinterJob, file.encoding=UTF-8, java.specification.version=1.8, java.class.path=/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/charsets.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/cldrdata.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/dnsns.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/jaccess.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/jfxrt.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/localedata.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/nashorn.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/sunec.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/sunjce_provider.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/sunpkcs11.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/zipfs.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/jce.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/jfr.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/jfxswt.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/jsse.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/management-agent.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/resources.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/rt.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/lib/ant-javafx.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/lib/dt.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/lib/javafx-mx.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/lib/jconsole.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/lib/packager.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/lib/sa-jdi.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/lib/tools.jar:/Users/yennanliu/JavaHelloWorld/target/classes:/Users/yennanliu/.m2/repository/joda-time/joda-time/2.9.2/joda-time-2.9.2.jar:/Users/yennanliu/.m2/repository/org/junit/jupiter/junit-jupiter/5.8.0-M1/junit-jupiter-5.8.0-M1.jar:/Users/yennanliu/.m2/repository/org/junit/jupiter/junit-jupiter-api/5.8.0-M1/junit-jupiter-api-5.8.0-M1.jar:/Users/yennanliu/.m2/repository/org/apiguardian/apiguardian-api/1.1.1/apiguardian-api-1.1.1.jar:/Users/yennanliu/.m2/repository/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar:/Users/yennanliu/.m2/repository/org/junit/platform/junit-platform-commons/1.8.0-M1/junit-platform-commons-1.8.0-M1.jar:/Users/yennanliu/.m2/repository/org/junit/jupiter/junit-jupiter-params/5.8.0-M1/junit-jupiter-params-5.8.0-M1.jar:/Users/yennanliu/.m2/repository/org/junit/jupiter/junit-jupiter-engine/5.8.0-M1/junit-jupiter-engine-5.8.0-M1.jar:/Users/yennanliu/.m2/repository/org/junit/platform/junit-platform-engine/1.8.0-M1/junit-platform-engine-1.8.0-M1.jar:/Users/yennanliu/.m2/repository/org/jetbrains/kotlin/kotlin-stdlib-jdk8/1.4.20/kotlin-stdlib-jdk8-1.4.20.jar:/Users/yennanliu/.m2/repository/org/jetbrains/kotlin/kotlin-stdlib/1.4.20/kotlin-stdlib-1.4.20.jar:/Users/yennanliu/.m2/repository/org/jetbrains/kotlin/kotlin-stdlib-common/1.4.20/kotlin-stdlib-common-1.4.20.jar:/Users/yennanliu/.m2/repository/org/jetbrains/annotations/13.0/annotations-13.0.jar:/Users/yennanliu/.m2/repository/org/jetbrains/kotlin/kotlin-stdlib-jdk7/1.4.20/kotlin-stdlib-jdk7-1.4.20.jar:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar, user.name=yennanliu, java.vm.specification.version=1.8, sun.java.command=Advances.SystemDemo1, java.home=/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre, sun.arch.data.model=64, user.language=en, java.specification.vendor=Oracle Corporation, awt.toolkit=sun.lwawt.macosx.LWCToolkit, java.vm.info=mixed mode, java.version=1.8.0_292, java.ext.dirs=/Users/yennanliu/Library/Java/Extensions:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java, sun.boot.class.path=/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/resources.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/rt.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/sunrsasign.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/jsse.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/jce.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/charsets.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/jfr.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/classes, java.vendor=BellSoft, file.separator=/, java.vendor.url.bug=https://bell-sw.com/support, sun.io.unicode.encoding=UnicodeBig, sun.cpu.endian=little, socksNonProxyHosts=local|*.local|169.254/16|*.169.254/16, ftp.nonProxyHosts=local|*.local|169.254/16|*.169.254/16, sun.cpu.isalist=}
+ System.out.println(System.getProperties()); // {java.runtime.name=OpenJDK Runtime Environment,
+ // sun.boot.library.path=/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib, java.vm.version=25.292-b10, gopherProxySet=false, java.vm.vendor=BellSoft, java.vendor.url=https://bell-sw.com/, path.separator=:, java.vm.name=OpenJDK 64-Bit Server VM, file.encoding.pkg=sun.io, user.country=TW, sun.java.launcher=SUN_STANDARD, sun.os.patch.level=unknown, java.vm.specification.name=Java Virtual Machine Specification, user.dir=/Users/yennanliu/JavaHelloWorld, java.runtime.version=1.8.0_292-b10, java.awt.graphicsenv=sun.awt.CGraphicsEnvironment, java.endorsed.dirs=/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/endorsed, os.arch=aarch64, java.io.tmpdir=/var/folders/tz/5r4lbzxj5hs5q87gwdwyjnph0000gn/T/, line.separator= java.vm.specification.vendor=Oracle Corporation, os.name=Mac OS X, sun.jnu.encoding=UTF-8, java.library.path=/Users/yennanliu/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:., java.specification.name=Java Platform API Specification, java.class.version=52.0, sun.management.compiler=HotSpot 64-Bit Tiered Compilers, os.version=11.6, http.nonProxyHosts=local|*.local|169.254/16|*.169.254/16, user.home=/Users/yennanliu, user.timezone=, java.awt.printerjob=sun.lwawt.macosx.CPrinterJob, file.encoding=UTF-8, java.specification.version=1.8, java.class.path=/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/charsets.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/cldrdata.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/dnsns.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/jaccess.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/jfxrt.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/localedata.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/nashorn.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/sunec.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/sunjce_provider.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/sunpkcs11.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext/zipfs.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/jce.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/jfr.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/jfxswt.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/jsse.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/management-agent.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/resources.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/rt.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/lib/ant-javafx.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/lib/dt.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/lib/javafx-mx.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/lib/jconsole.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/lib/packager.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/lib/sa-jdi.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/lib/tools.jar:/Users/yennanliu/JavaHelloWorld/target/classes:/Users/yennanliu/.m2/repository/joda-time/joda-time/2.9.2/joda-time-2.9.2.jar:/Users/yennanliu/.m2/repository/org/junit/jupiter/junit-jupiter/5.8.0-M1/junit-jupiter-5.8.0-M1.jar:/Users/yennanliu/.m2/repository/org/junit/jupiter/junit-jupiter-api/5.8.0-M1/junit-jupiter-api-5.8.0-M1.jar:/Users/yennanliu/.m2/repository/org/apiguardian/apiguardian-api/1.1.1/apiguardian-api-1.1.1.jar:/Users/yennanliu/.m2/repository/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar:/Users/yennanliu/.m2/repository/org/junit/platform/junit-platform-commons/1.8.0-M1/junit-platform-commons-1.8.0-M1.jar:/Users/yennanliu/.m2/repository/org/junit/jupiter/junit-jupiter-params/5.8.0-M1/junit-jupiter-params-5.8.0-M1.jar:/Users/yennanliu/.m2/repository/org/junit/jupiter/junit-jupiter-engine/5.8.0-M1/junit-jupiter-engine-5.8.0-M1.jar:/Users/yennanliu/.m2/repository/org/junit/platform/junit-platform-engine/1.8.0-M1/junit-platform-engine-1.8.0-M1.jar:/Users/yennanliu/.m2/repository/org/jetbrains/kotlin/kotlin-stdlib-jdk8/1.4.20/kotlin-stdlib-jdk8-1.4.20.jar:/Users/yennanliu/.m2/repository/org/jetbrains/kotlin/kotlin-stdlib/1.4.20/kotlin-stdlib-1.4.20.jar:/Users/yennanliu/.m2/repository/org/jetbrains/kotlin/kotlin-stdlib-common/1.4.20/kotlin-stdlib-common-1.4.20.jar:/Users/yennanliu/.m2/repository/org/jetbrains/annotations/13.0/annotations-13.0.jar:/Users/yennanliu/.m2/repository/org/jetbrains/kotlin/kotlin-stdlib-jdk7/1.4.20/kotlin-stdlib-jdk7-1.4.20.jar:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar, user.name=yennanliu, java.vm.specification.version=1.8, sun.java.command=Advances.SystemDemo1, java.home=/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre, sun.arch.data.model=64, user.language=en, java.specification.vendor=Oracle Corporation, awt.toolkit=sun.lwawt.macosx.LWCToolkit, java.vm.info=mixed mode, java.version=1.8.0_292, java.ext.dirs=/Users/yennanliu/Library/Java/Extensions:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/ext:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java, sun.boot.class.path=/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/resources.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/rt.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/sunrsasign.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/jsse.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/jce.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/charsets.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/lib/jfr.jar:/Users/yennanliu/Library/Java/JavaVirtualMachines/liberica-1.8.0_292/jre/classes, java.vendor=BellSoft, file.separator=/, java.vendor.url.bug=https://bell-sw.com/support, sun.io.unicode.encoding=UnicodeBig, sun.cpu.endian=little, socksNonProxyHosts=local|*.local|169.254/16|*.169.254/16, ftp.nonProxyHosts=local|*.local|169.254/16|*.169.254/16, sun.cpu.isalist=}
System.out.println(System.getProperties().get("java.version"));
System.out.println(System.getProperties().get("java.home"));
System.out.println(System.getProperties().get("os.home"));
diff --git a/src/main/java/Advances/ThreadCommunication2/ProductTest.java b/src/main/java/Advances/ThreadCommunication2/ProductTest.java
index b74aad8d..ef8aacd4 100644
--- a/src/main/java/Advances/ThreadCommunication2/ProductTest.java
+++ b/src/main/java/Advances/ThreadCommunication2/ProductTest.java
@@ -2,157 +2,151 @@
// https://www.youtube.com/watch?v=97HVF6GT0AI&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=441
-
/**
- * Thread Communication example 2 : producer-consumer question
- *
- * - 1) Producer send the product to clerk, and consumer will take the products,
- * the clerks can only maintain fixed amount of the product (e.g. 20). Producers
- * need to wait till there is a space for storage before creating more products.
- * Consumers need to wait till there is available products
+ * Thread Communication example 2 : producer-consumer question
*
+ *
- 1) Producer send the product to clerk, and consumer will take the products, the clerks can
+ * only maintain fixed amount of the product (e.g. 20). Producers need to wait till there is a space
+ * for storage before creating more products. Consumers need to wait till there is available
+ * products
*
- * - 2) Analysis:
- * - multi thread ? -> yes, consumer multi thread, producer multi threads
- * - thread safety ? -> yes, there is shared values
- * - clerk
- * - product, product amount..
- * - how to solve thread safety ? -> synchronized methods, we have 2 ways
- * - synchronized code block
- * - synchronized method
- * - lock
+ *
- 2) Analysis: - multi thread ? -> yes, consumer multi thread, producer multi threads - thread
+ * safety ? -> yes, there is shared values - clerk - product, product amount.. - how to solve thread
+ * safety ? -> synchronized methods, we have 2 ways - synchronized code block - synchronized method
+ * - lock
*
- * - thready communication ? -> yes
- *
- * - 3) There are 2 cases we need to solve:
- * - Producer is faster than consumer : consumer may miss some product (data)
- * - Producer is slower than consumer : some consumers make take the same product (data)
+ *
- thready communication ? -> yes
*
+ *
- 3) There are 2 cases we need to solve: - Producer is faster than consumer : consumer may
+ * miss some product (data) - Producer is slower than consumer : some consumers make take the same
+ * product (data)
*/
// entry point
public class ProductTest {
- public static void main(String[] args) {
+ public static void main(String[] args) {
- // run
- Clerk clerk = new Clerk();
+ // run
+ Clerk clerk = new Clerk();
- Producer p1 = new Producer(clerk);
- p1.setName("Producer-1");
+ Producer p1 = new Producer(clerk);
+ p1.setName("Producer-1");
- Consumer c1 = new Consumer(clerk);
- c1.setName("Consumer-1");
+ Consumer c1 = new Consumer(clerk);
+ c1.setName("Consumer-1");
- Consumer c2 = new Consumer(clerk); // optional : add 1 more consumer
- c2.setName("Consumer-2");
+ Consumer c2 = new Consumer(clerk); // optional : add 1 more consumer
+ c2.setName("Consumer-2");
- p1.start();
- c1.start();
- c2.start();
- }
+ p1.start();
+ c1.start();
+ c2.start();
+ }
}
/** clerk */
-class Clerk{
-
- // attr
- private int productCount = 0;
-
- // method
- // produce product
- public synchronized void produceProduct() {
- if (productCount < 20){
- productCount += 1;
- System.out.println(Thread.currentThread().getName()+ " starts producing " + productCount + " product ...");
-
- /** notify consumer after producer produces 1 product */
- notify();
- }else{
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
+class Clerk {
+
+ // attr
+ private int productCount = 0;
+
+ // method
+ // produce product
+ public synchronized void produceProduct() {
+ if (productCount < 20) {
+ productCount += 1;
+ System.out.println(
+ Thread.currentThread().getName() + " starts producing " + productCount + " product ...");
+
+ /** notify consumer after producer produces 1 product */
+ notify();
+ } else {
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
}
-
- // consume product
- public synchronized void consumeProduct() {
- if (productCount > 0){
- System.out.println(Thread.currentThread().getName()+ " starts consuming " + productCount + " product ...");
- productCount -= 1;
-
- /** notify producer after consumer consumes 1 product */
- notify();
- }else{
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
+ }
+
+ // consume product
+ public synchronized void consumeProduct() {
+ if (productCount > 0) {
+ System.out.println(
+ Thread.currentThread().getName() + " starts consuming " + productCount + " product ...");
+ productCount -= 1;
+
+ /** notify producer after consumer consumes 1 product */
+ notify();
+ } else {
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
}
+ }
}
/** producer */
-class Producer extends Thread{
+class Producer extends Thread {
- // attr
- private Clerk clerk;
+ // attr
+ private final Clerk clerk;
- // constructor
- public Producer(Clerk clerk){
- this.clerk = clerk;
- }
+ // constructor
+ public Producer(Clerk clerk) {
+ this.clerk = clerk;
+ }
- // method
- @Override
- public void run() {
-
- super.run();
- System.out.println(this.getName() + " Producer produces product ...");
+ // method
+ @Override
+ public void run() {
- while (true){
+ super.run();
+ System.out.println(this.getName() + " Producer produces product ...");
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
+ while (true) {
- clerk.produceProduct();
- }
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+
+ clerk.produceProduct();
}
+ }
}
/** consumer */
class Consumer extends Thread {
- // attr
- private Clerk clerk;
+ // attr
+ private final Clerk clerk;
- // constructor
- public Consumer(Clerk clerk){
- this.clerk = clerk;
- }
+ // constructor
+ public Consumer(Clerk clerk) {
+ this.clerk = clerk;
+ }
- // method
- @Override
- public void run() {
+ // method
+ @Override
+ public void run() {
- super.run();
- System.out.println(this.getName() + " Consumer consumes product ...");
+ super.run();
+ System.out.println(this.getName() + " Consumer consumes product ...");
- while (true){
+ while (true) {
- try {
- //Thread.sleep(10);
- Thread.sleep(20); // make consumer a bit slower than producer
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
+ try {
+ // Thread.sleep(10);
+ Thread.sleep(20); // make consumer a bit slower than producer
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
- clerk.consumeProduct();
- }
+ clerk.consumeProduct();
}
+ }
}
diff --git a/src/main/java/Advances/ThreadDemo4/ThreadMethodDemo3.java b/src/main/java/Advances/ThreadDemo4/ThreadMethodDemo3.java
index aec3eaad..233d5c60 100644
--- a/src/main/java/Advances/ThreadDemo4/ThreadMethodDemo3.java
+++ b/src/main/java/Advances/ThreadDemo4/ThreadMethodDemo3.java
@@ -33,7 +33,7 @@ public void run() {
/**
* `yield` will release current CPU execution ->(other thread may get the lock then run )
*/
- this.yield();
+ yield();
}
}
}
diff --git a/src/main/java/Advances/ThreadDemo6/CallableDemo1.java b/src/main/java/Advances/ThreadDemo6/CallableDemo1.java
index c36035fe..57ba31f1 100644
--- a/src/main/java/Advances/ThreadDemo6/CallableDemo1.java
+++ b/src/main/java/Advances/ThreadDemo6/CallableDemo1.java
@@ -66,7 +66,7 @@ public Object call() throws Exception {
}
// the call() method can have return value (optional)
return sum; // NOTE : int (sum) is NOT sub type of Object (Object call()), but we transform int
- // to Integer
+ // to Integer
// return _;
}
}
diff --git a/src/main/java/Advances/ThreadPool1/demo1.java b/src/main/java/Advances/ThreadPool1/demo1.java
index 5311aa70..f8db1f53 100644
--- a/src/main/java/Advances/ThreadPool1/demo1.java
+++ b/src/main/java/Advances/ThreadPool1/demo1.java
@@ -6,68 +6,55 @@
import java.util.concurrent.Executors;
/**
- * Demo1
- * Create thread method 4 : thread pool (basics)
+ * Demo1 Create thread method 4 : thread pool (basics)
*
- * * Pros
- * 1) fast response speed (reduce creating new thread time)
- * 2) reduce resource cost (reuse used thread in pool, no need to create new ones every time)
- * 3) easy to manage
- * - corePoolSize : core pool size
- * - maximumPoolSize : max thread amount
- * - keepAliveTime : how long thread got terminated if no mission
- * ...
+ *
* Pros 1) fast response speed (reduce creating new thread time) 2) reduce resource cost (reuse
+ * used thread in pool, no need to create new ones every time) 3) easy to manage - corePoolSize :
+ * core pool size - maximumPoolSize : max thread amount - keepAliveTime : how long thread got
+ * terminated if no mission ...
*
- *
- * 1) methods we can create multi-thread ?
- * -> 4
- * - e.g.
- * - inherit Thread
- * - implement Runnable
- * - Callable + future
- * - thread pool
- * - https://blog.csdn.net/baihualindesu/article/details/89523837
+ *
1) methods we can create multi-thread ? -> 4 - e.g. - inherit Thread - implement Runnable -
+ * Callable + future - thread pool - https://blog.csdn.net/baihualindesu/article/details/89523837
*/
-
-class NumberThread implements Runnable{
-
- @Override
- public void run() {
- for (int i=0; i <= 100; i++){
- if (i % 2 == 0){
- System.out.println(Thread.currentThread().getName() + "-->" + i);
- }
- }
+class NumberThread implements Runnable {
+
+ @Override
+ public void run() {
+ for (int i = 0; i <= 100; i++) {
+ if (i % 2 == 0) {
+ System.out.println(Thread.currentThread().getName() + "-->" + i);
+ }
}
+ }
}
-class NumberThread2 implements Runnable{
+class NumberThread2 implements Runnable {
- @Override
- public void run() {
- for (int i=0; i <= 100; i++){
- if (i % 2 != 0){
- System.out.println(Thread.currentThread().getName() + "-->" + i);
- }
- }
+ @Override
+ public void run() {
+ for (int i = 0; i <= 100; i++) {
+ if (i % 2 != 0) {
+ System.out.println(Thread.currentThread().getName() + "-->" + i);
+ }
}
+ }
}
// entry point
public class demo1 {
- public static void main(String[] args) {
+ public static void main(String[] args) {
- // step 1) create a thread pool that can run 10 threads
- ExecutorService service = Executors.newFixedThreadPool(10);
+ // step 1) create a thread pool that can run 10 threads
+ ExecutorService service = Executors.newFixedThreadPool(10);
- // step 2) execute the thread (via thread pool).
- // NOTE : we need to offer instance implemented Runnable or Callable interface
- service.execute(new NumberThread()); // good to use with `Runnable`
- service.execute(new NumberThread2()); // good to use with `Runnable`
+ // step 2) execute the thread (via thread pool).
+ // NOTE : we need to offer instance implemented Runnable or Callable interface
+ service.execute(new NumberThread()); // good to use with `Runnable`
+ service.execute(new NumberThread2()); // good to use with `Runnable`
- //service.submit(Callable callable); // good to use with `Callable`
+ // service.submit(Callable callable); // good to use with `Callable`
- // step 3) shutdown thread pool
- service.shutdown();
- }
+ // step 3) shutdown thread pool
+ service.shutdown();
+ }
}
diff --git a/src/main/java/Advances/ThreadSafety2/demo1.java b/src/main/java/Advances/ThreadSafety2/demo1.java
index 489a2368..e1c331d6 100644
--- a/src/main/java/Advances/ThreadSafety2/demo1.java
+++ b/src/main/java/Advances/ThreadSafety2/demo1.java
@@ -25,7 +25,7 @@ class Window implements Runnable {
private int ticket = 100;
// step 1) define/instantiate a lock
- private ReentrantLock lock = new ReentrantLock();
+ private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
diff --git a/src/main/java/Advances/ThreadSafety3/AccountDemo1.java b/src/main/java/Advances/ThreadSafety3/AccountDemo1.java
index d29918fa..2e07cb3f 100644
--- a/src/main/java/Advances/ThreadSafety3/AccountDemo1.java
+++ b/src/main/java/Advances/ThreadSafety3/AccountDemo1.java
@@ -61,7 +61,7 @@ public synchronized void deposit(double amt) {
class Customer extends Thread {
// attr
- private Account acct;
+ private final Account acct;
// constructor
public Customer(Account acct) {
diff --git a/src/main/java/Advances/TreeMap/User.java b/src/main/java/Advances/TreeMap/User.java
index 44b5a2ec..077398b7 100644
--- a/src/main/java/Advances/TreeMap/User.java
+++ b/src/main/java/Advances/TreeMap/User.java
@@ -4,7 +4,7 @@
public class User implements Comparable {
private String name;
- private int age;
+ private final int age;
// constructor
public User(String name, int age) {
diff --git a/src/main/java/Advances/TreeMap/demo1.java b/src/main/java/Advances/TreeMap/demo1.java
index 85733531..3b534006 100644
--- a/src/main/java/Advances/TreeMap/demo1.java
+++ b/src/main/java/Advances/TreeMap/demo1.java
@@ -8,66 +8,65 @@
/** TreeMap demo 1 */
/**
- * 1) when add key-value to TreeMap, key needs to from the instances from SAME class
- * -> since it will do ordering by key
- * - natural ordering
- * - custom ordering
+ * 1) when add key-value to TreeMap, key needs to from the instances from SAME class -> since it
+ * will do ordering by key - natural ordering - custom ordering
*/
-
public class demo1 {
- /** demo : natural ordering */
- @Test
- public void test1(){
- TreeMap map = new TreeMap();
+ /** demo : natural ordering */
+ @Test
+ public void test1() {
+ TreeMap map = new TreeMap();
- User u1 = new User("kate",10);
- User u2 = new User("jane",20);
- User u3 = new User("rose",17);
+ User u1 = new User("kate", 10);
+ User u2 = new User("jane", 20);
+ User u3 = new User("rose", 17);
- map.put(u1, 99);
- map.put(u2, 60);
- map.put(u3, 64);
+ map.put(u1, 99);
+ map.put(u2, 60);
+ map.put(u3, 64);
- Set entrySet = map.entrySet();
- Iterator iterator1 = entrySet.iterator();
- while (iterator1.hasNext()){
- Object obj = iterator1.next();
- // elements in entrySet collection are all entry
- Map.Entry entry = (Map.Entry) obj;
- System.out.println(entry.getKey() + " ---> " + entry.getValue());
- }
+ Set entrySet = map.entrySet();
+ Iterator iterator1 = entrySet.iterator();
+ while (iterator1.hasNext()) {
+ Object obj = iterator1.next();
+ // elements in entrySet collection are all entry
+ Map.Entry entry = (Map.Entry) obj;
+ System.out.println(entry.getKey() + " ---> " + entry.getValue());
}
+ }
- /** demo : custom ordering */
- @Test
- public void test2(){
- TreeMap map = new TreeMap(new Comparator() {
- @Override
- public int compare(Object o1, Object o2) {
- if (o1 instanceof User && o2 instanceof User){
- User u1 = (User)o1;
- User u2 = (User)o2;
- return Integer.compare(u1.getAge(), u2.getAge());
+ /** demo : custom ordering */
+ @Test
+ public void test2() {
+ TreeMap map =
+ new TreeMap(
+ new Comparator() {
+ @Override
+ public int compare(Object o1, Object o2) {
+ if (o1 instanceof User && o2 instanceof User) {
+ User u1 = (User) o1;
+ User u2 = (User) o2;
+ return Integer.compare(u1.getAge(), u2.getAge());
}
throw new RuntimeException("input type mismatch");
- }
- });
+ }
+ });
- User u1 = new User("kate",10);
- User u2 = new User("jane",20);
- User u3 = new User("rose",17);
+ User u1 = new User("kate", 10);
+ User u2 = new User("jane", 20);
+ User u3 = new User("rose", 17);
- map.put(u1, 99);
- map.put(u2, 60);
- map.put(u3, 64);
+ map.put(u1, 99);
+ map.put(u2, 60);
+ map.put(u3, 64);
- Set entrySet = map.entrySet();
- Iterator iterator1 = entrySet.iterator();
- while (iterator1.hasNext()){
- Object obj = iterator1.next();
- // elements in entrySet collection are all entry
- Map.Entry entry = (Map.Entry) obj;
- System.out.println(entry.getKey() + " ---> " + entry.getValue());
- }
+ Set entrySet = map.entrySet();
+ Iterator iterator1 = entrySet.iterator();
+ while (iterator1.hasNext()) {
+ Object obj = iterator1.next();
+ // elements in entrySet collection are all entry
+ Map.Entry entry = (Map.Entry) obj;
+ System.out.println(entry.getKey() + " ---> " + entry.getValue());
}
+ }
}
diff --git a/src/main/java/Advances/internet/demo2.java b/src/main/java/Advances/internet/demo2.java
index b712e645..92269aba 100644
--- a/src/main/java/Advances/internet/demo2.java
+++ b/src/main/java/Advances/internet/demo2.java
@@ -2,8 +2,6 @@
// https://www.youtube.com/watch?v=GEGJuUUM_Zo&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=623
-import org.junit.jupiter.api.Test;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -11,6 +9,7 @@
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
+import org.junit.jupiter.api.Test;
/**
* Implement TCP internet protocol : demo 2
@@ -91,7 +90,7 @@ public void server() {
baos.write(buffer, 0, len);
}
- System.out.println(baos.toString());
+ System.out.println(baos);
System.out.println("receive msg from client : " + socket.getInetAddress().getHostAddress());
} catch (IOException e) {
diff --git a/src/main/java/Advances/internet/demo3.java b/src/main/java/Advances/internet/demo3.java
index 8667790b..21a86969 100644
--- a/src/main/java/Advances/internet/demo3.java
+++ b/src/main/java/Advances/internet/demo3.java
@@ -9,72 +9,71 @@
import org.junit.jupiter.api.Test;
/**
- * Implement TCP internet protocol : demo 3
+ * Implement TCP internet protocol : demo 3
*
- * 1) client sends doc, server saves it to local
+ *
1) client sends doc, server saves it to local
*/
-
// NOTE : should use "try-catch-finally" for exception handling (as demo2.java)
public class demo3 {
- // client
- @Test
- public void client() throws IOException {
-
- // step 1) create socket
- Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
+ // client
+ @Test
+ public void client() throws IOException {
- // step 2) create output stream
- OutputStream os = socket.getOutputStream();
+ // step 1) create socket
+ Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
- String srcFile = "src/main/java/Advances/internet/data.txt";
+ // step 2) create output stream
+ OutputStream os = socket.getOutputStream();
- // step 3) read file
- FileInputStream fis = new FileInputStream(new File(srcFile));
+ String srcFile = "src/main/java/Advances/internet/data.txt";
- // step 4) actual read op
- byte[] buffer = new byte[1024];
- int len;
- while((len = fis.read(buffer)) != -1){
- os.write(buffer, 0, len);
- }
+ // step 3) read file
+ FileInputStream fis = new FileInputStream(new File(srcFile));
- // step 5) close resources
- fis.close();
- os.close();
- socket.close();
+ // step 4) actual read op
+ byte[] buffer = new byte[1024];
+ int len;
+ while ((len = fis.read(buffer)) != -1) {
+ os.write(buffer, 0, len);
}
- // server
- @Test
- public void server() throws IOException {
+ // step 5) close resources
+ fis.close();
+ os.close();
+ socket.close();
+ }
- // step 1) create ServerSocket
- ServerSocket ss = new ServerSocket(9999);
+ // server
+ @Test
+ public void server() throws IOException {
- // step 2) get client socket
- Socket socket = ss.accept();
+ // step 1) create ServerSocket
+ ServerSocket ss = new ServerSocket(9999);
- // step 3) get client input stream
- InputStream is = socket.getInputStream();
+ // step 2) get client socket
+ Socket socket = ss.accept();
- String destFile = "src/main/java/Advances/internet/data_output.txt";
+ // step 3) get client input stream
+ InputStream is = socket.getInputStream();
- // step 4) create file output stream
- FileOutputStream fos = new FileOutputStream(destFile);
+ String destFile = "src/main/java/Advances/internet/data_output.txt";
- // step 5) read, write op
- byte[] buffer = new byte[1024];
- int len;
- while((len = is.read(buffer)) != -1){
- fos.write(buffer, 0, len);
- }
+ // step 4) create file output stream
+ FileOutputStream fos = new FileOutputStream(destFile);
- // step 6) close resources
- fos.close();
- is.close();
- socket.close();
- ss.close();
+ // step 5) read, write op
+ byte[] buffer = new byte[1024];
+ int len;
+ while ((len = is.read(buffer)) != -1) {
+ fos.write(buffer, 0, len);
}
+
+ // step 6) close resources
+ fos.close();
+ is.close();
+ socket.close();
+ ss.close();
+ }
}
diff --git a/src/main/java/Advances/internet/demo4.java b/src/main/java/Advances/internet/demo4.java
index 6d1784be..3058efae 100644
--- a/src/main/java/Advances/internet/demo4.java
+++ b/src/main/java/Advances/internet/demo4.java
@@ -10,96 +10,95 @@
import org.junit.jupiter.api.Test;
/**
- * Implement TCP internet protocol : demo 4
+ * Implement TCP internet protocol : demo 4
*
- * 1) client sends doc, server saves it to local, and return "success" to client, then close connection
+ *
1) client sends doc, server saves it to local, and return "success" to client, then close
+ * connection
*/
-
public class demo4 {
- // client
- @Test
- public void client() throws IOException {
-
- // step 1) create socket
- Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
-
- // step 2) create output stream
- OutputStream os = socket.getOutputStream();
-
- String srcFile = "src/main/java/Advances/internet/data.txt";
-
- // step 3) read file
- FileInputStream fis = new FileInputStream(new File(srcFile));
-
- // step 4) actual read op
- byte[] buffer = new byte[1024];
- int len;
- while((len = fis.read(buffer)) != -1){
- os.write(buffer, 0, len);
- }
-
- // NOTE !!! : shutdown socket when file transmitted completed (or will block socket)
- socket.shutdownOutput();
-
- // step 5) receive server's response, and print on terminal
- InputStream is = socket.getInputStream();
- // decode
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buffer2 = new byte[20];
- int len2;
- while((len2 = fis.read(buffer2)) != -1){
- baos.write(buffer2, 0, len2);
- }
-
- System.out.println("client msg >>>");
- // TODO : fix this
- System.out.println(baos.toString());
- //System.out.println("file received !! (msg from server)");
- System.out.println("client msg >>>");
-
- // step 6) close resources
- fis.close();
- os.close();
- socket.close();
+ // client
+ @Test
+ public void client() throws IOException {
+
+ // step 1) create socket
+ Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
+
+ // step 2) create output stream
+ OutputStream os = socket.getOutputStream();
+
+ String srcFile = "src/main/java/Advances/internet/data.txt";
+
+ // step 3) read file
+ FileInputStream fis = new FileInputStream(new File(srcFile));
+
+ // step 4) actual read op
+ byte[] buffer = new byte[1024];
+ int len;
+ while ((len = fis.read(buffer)) != -1) {
+ os.write(buffer, 0, len);
+ }
+
+ // NOTE !!! : shutdown socket when file transmitted completed (or will block socket)
+ socket.shutdownOutput();
+
+ // step 5) receive server's response, and print on terminal
+ InputStream is = socket.getInputStream();
+ // decode
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ byte[] buffer2 = new byte[20];
+ int len2;
+ while ((len2 = fis.read(buffer2)) != -1) {
+ baos.write(buffer2, 0, len2);
}
- // server
- @Test
- public void server() throws IOException {
+ System.out.println("client msg >>>");
+ // TODO : fix this
+ System.out.println(baos);
+ // System.out.println("file received !! (msg from server)");
+ System.out.println("client msg >>>");
- // step 1) create ServerSocket
- ServerSocket ss = new ServerSocket(9999);
+ // step 6) close resources
+ fis.close();
+ os.close();
+ socket.close();
+ }
- // step 2) get client socket
- Socket socket = ss.accept();
+ // server
+ @Test
+ public void server() throws IOException {
- // step 3) get client input stream
- InputStream is = socket.getInputStream();
+ // step 1) create ServerSocket
+ ServerSocket ss = new ServerSocket(9999);
- String destFile = "src/main/java/Advances/internet/data_output2.txt";
+ // step 2) get client socket
+ Socket socket = ss.accept();
- // step 4) create file output stream
- FileOutputStream fos = new FileOutputStream(destFile);
+ // step 3) get client input stream
+ InputStream is = socket.getInputStream();
- // step 5) read, write op
- byte[] buffer = new byte[1024];
- int len;
- while((len = is.read(buffer)) != -1){
- fos.write(buffer, 0, len);
- }
+ String destFile = "src/main/java/Advances/internet/data_output2.txt";
- // step 6) send response to client
- OutputStream os = socket.getOutputStream();
- System.out.println("file sent !! (server)");
- os.write("file received !! (msg from server)".getBytes());
+ // step 4) create file output stream
+ FileOutputStream fos = new FileOutputStream(destFile);
- // step 7) close resources
- fos.close();
- is.close();
- socket.close();
- ss.close();
- os.close();
+ // step 5) read, write op
+ byte[] buffer = new byte[1024];
+ int len;
+ while ((len = is.read(buffer)) != -1) {
+ fos.write(buffer, 0, len);
}
+ // step 6) send response to client
+ OutputStream os = socket.getOutputStream();
+ System.out.println("file sent !! (server)");
+ os.write("file received !! (msg from server)".getBytes());
+
+ // step 7) close resources
+ fos.close();
+ is.close();
+ socket.close();
+ ss.close();
+ os.close();
+ }
}
diff --git a/src/main/java/Advances/internet/demo5.java b/src/main/java/Advances/internet/demo5.java
index 9e872910..5a06e983 100644
--- a/src/main/java/Advances/internet/demo5.java
+++ b/src/main/java/Advances/internet/demo5.java
@@ -7,46 +7,46 @@
import org.junit.jupiter.api.Test;
/**
- * UDP intro & demo 1
+ * UDP intro & demo 1
*
- * 1) DatagramSocket, DatagramPacket class help UDP program implementation
- * 2) UDP info via DatagramSocket send and receiver.
- * -> However, system NOT Grantee when/whether such info can be sent to client side
+ *
1) DatagramSocket, DatagramPacket class help UDP program implementation 2) UDP info via
+ * DatagramSocket send and receiver. -> However, system NOT Grantee when/whether such info can be
+ * sent to client side
*
- * 3) DatagramPacket encapsulates UDP data msg, sender ip, address, receiver ip, address are included
- *
- * 4) Every UCP protocol has address info, so NO NEED to set up connection (with receiver), similar as delivery service
+ *
3) DatagramPacket encapsulates UDP data msg, sender ip, address, receiver ip, address are
+ * included
*
+ *
4) Every UCP protocol has address info, so NO NEED to set up connection (with receiver),
+ * similar as delivery service
*/
-
public class demo5 {
- @Test
- public void sender() throws IOException {
+ @Test
+ public void sender() throws IOException {
- DatagramSocket socket = new DatagramSocket();
+ DatagramSocket socket = new DatagramSocket();
- String str = "this is UDP msg";
- byte[] data = str.getBytes();
- InetAddress inet = InetAddress.getLocalHost();
- DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);
+ String str = "this is UDP msg";
+ byte[] data = str.getBytes();
+ InetAddress inet = InetAddress.getLocalHost();
+ DatagramPacket packet = new DatagramPacket(data, 0, data.length, inet, 9090);
- socket.send(packet);
+ socket.send(packet);
- socket.close();
- }
+ socket.close();
+ }
- @Test
- public void receiver() throws IOException {
+ @Test
+ public void receiver() throws IOException {
- DatagramSocket socket = new DatagramSocket(9090);
+ DatagramSocket socket = new DatagramSocket(9090);
- byte[] buffer = new byte[100];
- DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
- socket.receive(packet);
+ byte[] buffer = new byte[100];
+ DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
+ socket.receive(packet);
- System.out.println(new String(packet.getData(),0, packet.getLength()));
+ System.out.println(new String(packet.getData(), 0, packet.getLength()));
- socket.close();
- }
+ socket.close();
+ }
}
diff --git a/src/main/java/Basics/AbstractDemo3/PersonTest.java b/src/main/java/Basics/AbstractDemo3/PersonTest.java
index 9403b3bf..081f4792 100644
--- a/src/main/java/Basics/AbstractDemo3/PersonTest.java
+++ b/src/main/java/Basics/AbstractDemo3/PersonTest.java
@@ -34,13 +34,11 @@ public static void main(String[] args) {
public void eat() {
System.out.println("new eat !!");
}
- ;
- @Override
+ @Override
public void sleep() {
System.out.println("new sleep !!");
}
- ;
};
method1(p);
@@ -78,9 +76,7 @@ public static void method1(Person p) {
class Worker2 extends Person {
@Override
public void eat() {}
- ;
- @Override
+ @Override
public void sleep() {}
- ;
}
diff --git a/src/main/java/Basics/Constructor1.java b/src/main/java/Basics/Constructor1.java
index b6857431..ccd563c0 100644
--- a/src/main/java/Basics/Constructor1.java
+++ b/src/main/java/Basics/Constructor1.java
@@ -52,6 +52,7 @@ public Person_1() { // constructor1
public Person_1(String name) { // constructor2
this.name = name;
}
+
public Person_1(String name, int age) { // constructor3
this.name = name;
this.age = age;
diff --git a/src/main/java/Basics/CustomerCRM/service/CustomerList.java b/src/main/java/Basics/CustomerCRM/service/CustomerList.java
index 9b8e4644..6bfa6ae6 100644
--- a/src/main/java/Basics/CustomerCRM/service/CustomerList.java
+++ b/src/main/java/Basics/CustomerCRM/service/CustomerList.java
@@ -13,7 +13,7 @@
public class CustomerList {
// attr
- private Customer[] customers; // the array save customer information
+ private final Customer[] customers; // the array save customer information
private int total = 0; // how many customer in the list
// constructor
diff --git a/src/main/java/Basics/CustomerCRM/service/TeamService.java b/src/main/java/Basics/CustomerCRM/service/TeamService.java
index d8e6cb45..01713471 100644
--- a/src/main/java/Basics/CustomerCRM/service/TeamService.java
+++ b/src/main/java/Basics/CustomerCRM/service/TeamService.java
@@ -16,7 +16,7 @@ public class TeamService {
// attr
private static int counter = 1; // increasing, for member id
private final int MAX_MEMBER = 5; // mex members in a dev team
- private Programmer[] team = new Programmer[MAX_MEMBER]; // storage dev team members
+ private final Programmer[] team = new Programmer[MAX_MEMBER]; // storage dev team members
private int total; // current total member count in dev team
// getter, setter
diff --git a/src/main/java/Basics/CustomerCRM/utils/CMUtility.java b/src/main/java/Basics/CustomerCRM/utils/CMUtility.java
index e803185b..099f8359 100644
--- a/src/main/java/Basics/CustomerCRM/utils/CMUtility.java
+++ b/src/main/java/Basics/CustomerCRM/utils/CMUtility.java
@@ -11,7 +11,7 @@
/** CMUtility tool: 将不同的功能封装为方法,就是可以直接通过调用方法使用它的功能,而无需考虑具体的功能实现细节。 */
public class CMUtility {
- private static Scanner scanner = new Scanner(System.in);
+ private static final Scanner scanner = new Scanner(System.in);
/** 用于界面菜单的选择。该方法读取键盘,如果用户键入’1’-’5’中的任意字符,则方法返回。返回值为用户键入字符。 */
public static char readMenuSelection() {
diff --git a/src/main/java/Basics/CustomerCRM/view/CustomerView.java b/src/main/java/Basics/CustomerCRM/view/CustomerView.java
index ee01042f..781db132 100644
--- a/src/main/java/Basics/CustomerCRM/view/CustomerView.java
+++ b/src/main/java/Basics/CustomerCRM/view/CustomerView.java
@@ -17,7 +17,7 @@
import Basics.CustomerCRM.utils.CMUtility;
public class CustomerView {
- private CustomerList customerList = new CustomerList(10);
+ private final CustomerList customerList = new CustomerList(10);
// constructor
@@ -37,9 +37,8 @@ public static void main(String[] args) {
CustomerView customerView = new CustomerView();
customerView.enterMainMenu();
}
- ;
- /***
+ /***
* show customer app interface
*/
private void enterMainMenu() {
@@ -82,9 +81,8 @@ private void enterMainMenu() {
// isFlag = false;
}
}
- ;
- /***
+ /***
* add new customer
*/
private void addNewCustomer() {
@@ -118,9 +116,8 @@ private void addNewCustomer() {
System.out.println("add new customer failed !");
}
}
- ;
- /***
+ /***
* modify customer
*/
private void modifyCustomer() {
@@ -151,10 +148,8 @@ private void modifyCustomer() {
System.out.println("Customer name(" + cust.getName() + "):");
String name =
CMUtility.readString(
- 10,
- cust
- .getName()); // if user don't input new name, but just press enter -> use the
- // original customer name by default
+ 10, cust.getName()); // if user don't input new name, but just press enter -> use the
+ // original customer name by default
System.out.println("Customer gender(" + cust.getGender() + "):");
char gender = CMUtility.readChar(cust.getGender());
@@ -177,9 +172,8 @@ private void modifyCustomer() {
System.out.println("--------------------- Modify Customer Failed ! --------------------- \n");
}
}
- ;
- /***
+ /***
* delete customer
*/
private void deleteCustomer() {
@@ -222,9 +216,8 @@ private void deleteCustomer() {
return;
}
}
- ;
- /***
+ /***
* list all customer
*/
private void listAllCustomer() {
diff --git a/src/main/java/Basics/CustomerCRM/view/TeamView.java b/src/main/java/Basics/CustomerCRM/view/TeamView.java
index c909f9ac..2cf528f6 100644
--- a/src/main/java/Basics/CustomerCRM/view/TeamView.java
+++ b/src/main/java/Basics/CustomerCRM/view/TeamView.java
@@ -14,8 +14,8 @@
public class TeamView {
// attr
- private NameListService listSvc = new NameListService();
- private TeamService teamSvc = new TeamService();
+ private final NameListService listSvc = new NameListService();
+ private final TeamService teamSvc = new TeamService();
/** entry point */
public static void main(String[] args) {
diff --git a/src/main/java/Basics/DynamicNumVar1.java b/src/main/java/Basics/DynamicNumVar1.java
index 609f0e50..727b9bc4 100644
--- a/src/main/java/Basics/DynamicNumVar1.java
+++ b/src/main/java/Basics/DynamicNumVar1.java
@@ -11,7 +11,7 @@ public static void main(String[] args) {
test.show("i", "love", "you");
test.show();
// do it via Anonymous Object
- test.show(new String[] {"AA", "BB", "CC"});
+ test.show("AA", "BB", "CC");
// String[] str_ = new String[]{"AA", "BB", "CC"};
// test.show(str_);
diff --git a/src/main/java/Basics/EmployeeCRM/team/domain/Architect.java b/src/main/java/Basics/EmployeeCRM/team/domain/Architect.java
index 8e3723e4..d9218191 100644
--- a/src/main/java/Basics/EmployeeCRM/team/domain/Architect.java
+++ b/src/main/java/Basics/EmployeeCRM/team/domain/Architect.java
@@ -36,6 +36,6 @@ public String toString() {
+ getStatus()
+ " bonus="
+ getBonus(); // ",stock=" + stock + super.getEquipment().getDescription(); // TODO : fix
- // this
+ // this
}
}
diff --git a/src/main/java/Basics/EmployeeCRM/team/domain/Programmer.java b/src/main/java/Basics/EmployeeCRM/team/domain/Programmer.java
index be2cce5e..4f1a247d 100644
--- a/src/main/java/Basics/EmployeeCRM/team/domain/Programmer.java
+++ b/src/main/java/Basics/EmployeeCRM/team/domain/Programmer.java
@@ -4,57 +4,62 @@
import Basics.EmployeeCRM.team.service.Status;
-public class Programmer extends Employee{
-
- // attr
- private int memberId; // dev team id
- // NOTE : Status here is user defined
- private Status status = Status.FREE; // employee status : BUSY, FREE, VOCATION...
- private Equipment equipment;
-
- // constructor
- public Programmer(){
- super();
- }
-
- public Programmer(int id, String name, int age, double salary, Equipment equipment){
- // NOTE here
- super(id, name, age, salary);
- this.equipment = equipment;
- }
-
- // getter, setter
- public int getMemberId() {
- return memberId;
- }
-
- public void setMemberId(int memberId) {
- this.memberId = memberId;
- }
-
- public Status getStatus() {
- return status;
- }
-
- public void setStatus(Status status) {
- this.status = status;
- }
-
- public Equipment getEquipment() {
- return equipment;
- }
-
- public void setEquipment(Equipment equipment) {
- this.equipment = equipment;
- }
-
- // method
-
- @Override
- public String toString() {
- return super.getDetails() + " , " +
- "memberId=" + memberId +
- ", status=" + status + "\t\t\t" +
- ", equipment=" + equipment.getDescription();
- }
+public class Programmer extends Employee {
+
+ // attr
+ private int memberId; // dev team id
+ // NOTE : Status here is user defined
+ private Status status = Status.FREE; // employee status : BUSY, FREE, VOCATION...
+ private Equipment equipment;
+
+ // constructor
+ public Programmer() {
+ super();
+ }
+
+ public Programmer(int id, String name, int age, double salary, Equipment equipment) {
+ // NOTE here
+ super(id, name, age, salary);
+ this.equipment = equipment;
+ }
+
+ // getter, setter
+ public int getMemberId() {
+ return memberId;
+ }
+
+ public void setMemberId(int memberId) {
+ this.memberId = memberId;
+ }
+
+ public Status getStatus() {
+ return status;
+ }
+
+ public void setStatus(Status status) {
+ this.status = status;
+ }
+
+ public Equipment getEquipment() {
+ return equipment;
+ }
+
+ public void setEquipment(Equipment equipment) {
+ this.equipment = equipment;
+ }
+
+ // method
+
+ @Override
+ public String toString() {
+ return super.getDetails()
+ + " , "
+ + "memberId="
+ + memberId
+ + ", status="
+ + status
+ + "\t\t\t"
+ + ", equipment="
+ + equipment.getDescription();
+ }
}
diff --git a/src/main/java/Basics/EmployeeCRM/team/service/NameListService.java b/src/main/java/Basics/EmployeeCRM/team/service/NameListService.java
index 53ca6453..96c15d9e 100644
--- a/src/main/java/Basics/EmployeeCRM/team/service/NameListService.java
+++ b/src/main/java/Basics/EmployeeCRM/team/service/NameListService.java
@@ -15,7 +15,7 @@
public class NameListService {
// attr
- private Employee[] employees;
+ private final Employee[] employees;
// constructor
diff --git a/src/main/java/Basics/EmployeeCRM/team/service/Status.java b/src/main/java/Basics/EmployeeCRM/team/service/Status.java
index d07a01ed..0270e831 100644
--- a/src/main/java/Basics/EmployeeCRM/team/service/Status.java
+++ b/src/main/java/Basics/EmployeeCRM/team/service/Status.java
@@ -3,7 +3,6 @@
// https://www.youtube.com/watch?v=rN0byZHtGw8&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=390
// https://www.youtube.com/watch?v=mwg4N3epx9Y&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=502
-import javax.print.attribute.standard.MediaSize;
/**
* class defines employee status
@@ -45,5 +44,5 @@
public enum Status {
FREE,
BUSY,
- VOCATION;
+ VOCATION
}
diff --git a/src/main/java/Basics/EmployeeCRM/team/service/TeamService.java b/src/main/java/Basics/EmployeeCRM/team/service/TeamService.java
index 3e5d5af0..d760b70b 100644
--- a/src/main/java/Basics/EmployeeCRM/team/service/TeamService.java
+++ b/src/main/java/Basics/EmployeeCRM/team/service/TeamService.java
@@ -12,7 +12,7 @@ public class TeamService {
// attr
private static int counter = 1; // increasing, for member id
private final int MAX_MEMBER = 5; // mex members in a dev team
- private Programmer[] team = new Programmer[MAX_MEMBER]; // storage dev team members
+ private final Programmer[] team = new Programmer[MAX_MEMBER]; // storage dev team members
private int total; // current total member count in dev team
// getter, setter
diff --git a/src/main/java/Basics/EmployeeCRM/team/utils/TSUtility.java b/src/main/java/Basics/EmployeeCRM/team/utils/TSUtility.java
index 8c0f2246..cfa5dbeb 100644
--- a/src/main/java/Basics/EmployeeCRM/team/utils/TSUtility.java
+++ b/src/main/java/Basics/EmployeeCRM/team/utils/TSUtility.java
@@ -6,7 +6,7 @@
public class TSUtility {
- private static Scanner scanner = new Scanner(System.in);
+ private static final Scanner scanner = new Scanner(System.in);
/**
* @Description 该方法读取键盘,如果用户键入’1’-’4’中的任意字符,则方法返回。返回值为用户键入字符。
diff --git a/src/main/java/Basics/EmployeeCRM/team/view/TeamView.java b/src/main/java/Basics/EmployeeCRM/team/view/TeamView.java
index cc6449ba..b1d16de7 100644
--- a/src/main/java/Basics/EmployeeCRM/team/view/TeamView.java
+++ b/src/main/java/Basics/EmployeeCRM/team/view/TeamView.java
@@ -2,7 +2,6 @@
// https://www.youtube.com/watch?v=mwg4N3epx9Y&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=502
-
import Basics.EmployeeCRM.team.domain.Employee;
import Basics.EmployeeCRM.team.service.NameListService;
import Basics.EmployeeCRM.team.service.TeamException;
@@ -11,118 +10,119 @@
public class TeamView {
- // attr
- private NameListService listSvc = new NameListService();
- private TeamService teamSvc = new TeamService();
-
- /** entry point */
- public static void main(String[] args){
- TeamView view = new TeamView();
- view.enterMainMenu();
+ // attr
+ private final NameListService listSvc = new NameListService();
+ private final TeamService teamSvc = new TeamService();
+
+ /** entry point */
+ public static void main(String[] args) {
+ TeamView view = new TeamView();
+ view.enterMainMenu();
+ }
+
+ // method
+ public void enterMainMenu() {
+
+ // if keep looping
+ boolean loopFlag = true;
+ char menu = 0;
+
+ while (loopFlag) {
+
+ if (menu != '1') {
+ listAllEmployees();
+ }
+
+ System.out.println(
+ "1) Employee List 2) Add Member 3) Remove Member 4) Exist. Please select (1 to 4)\n");
+
+ menu = TSUtility.readMenuSelection();
+
+ switch (menu) {
+ case '1':
+ getTeam();
+ break;
+ case '2':
+ addMember();
+ break;
+ case '3':
+ deleteMember();
+ break;
+ case '4':
+ System.out.println("Exit ? (Y/N) ");
+ char isExist = TSUtility.readConfirmSelection();
+ if (isExist == 'Y') {
+ loopFlag = false;
+ }
+ break;
+ }
}
+ }
- // method
- public void enterMainMenu(){
-
- // if keep looping
- boolean loopFlag = true;
- char menu = 0;
-
- while(loopFlag){
-
- if (menu != '1'){
- listAllEmployees();
- }
-
- System.out.println("1) Employee List 2) Add Member 3) Remove Member 4) Exist. Please select (1 to 4)\n");
-
- menu = TSUtility.readMenuSelection();
-
- switch (menu){
- case '1':
- getTeam();
- break;
- case '2':
- addMember();
- break;
- case '3':
- deleteMember();
- break;
- case '4':
- System.out.println("Exit ? (Y/N) ");
- char isExist = TSUtility.readConfirmSelection();
- if (isExist == 'Y'){
- loopFlag = false;
- }
- break;
- }
- }
- }
+ /** show all employees */
+ private void listAllEmployees() {
+
+ System.out.println("--------------------- List All Employees --------------------- \n");
- /** show all employees */
- private void listAllEmployees(){
+ Employee[] employees = listSvc.getAllEmployees();
- System.out.println("--------------------- List All Employees --------------------- \n");
+ if (employees == null || employees.length == 0) {
- Employee[] employees = listSvc.getAllEmployees();
+ System.out.println("No employee in company !");
+ } else {
- if (employees == null || employees.length == 0){
+ System.out.println("ID\tName\tAge\tSalary\tPosition\tStatus\tBonus\tStock\tDevice");
- System.out.println("No employee in company !");
- }else{
+ for (int i = 0; i < employees.length; i++) {
+ System.out.println(employees[i]);
+ }
+ }
- System.out.println("ID\tName\tAge\tSalary\tPosition\tStatus\tBonus\tStock\tDevice");
+ System.out.println("--------------------- List All Employees --------------------- \n");
+ }
- for (int i =0; i < employees.length; i++){
- System.out.println(employees[i]);
- }
- }
+ private void getTeam() {
+ System.out.println("getTeam");
+ }
- System.out.println("--------------------- List All Employees --------------------- \n");
- }
+ private void addMember() {
- private void getTeam(){
- System.out.println("getTeam");
+ System.out.println("--------------------- Add Member --------------------- \n");
+ System.out.println("Plz enter the to-add member id");
+ int id = TSUtility.readInt();
+
+ try {
+ Employee emp = listSvc.getEmployee(id);
+ teamSvc.addMember(emp);
+ System.out.println("add member OK !");
+ TSUtility.readReturn();
+ } catch (TeamException e) {
+ System.out.println("add member failed ! " + e.getMessage());
}
+ }
+
+ private void deleteMember() {
+ System.out.println("--------------------- Delete Member --------------------- \n");
- private void addMember(){
+ System.out.println("Plz enter the to-delete member id");
+ int memberId = TSUtility.readInt();
- System.out.println("--------------------- Add Member --------------------- \n");
- System.out.println("Plz enter the to-add member id");
- int id = TSUtility.readInt();
+ System.out.println("Confirm to Delete ? (Y/N)");
+ char isDelete = TSUtility.readConfirmSelection();
- try {
- Employee emp = listSvc.getEmployee(id);
- teamSvc.addMember(emp);
- System.out.println("add member OK !");
- TSUtility.readReturn();
- } catch (TeamException e) {
- System.out.println("add member failed ! " + e.getMessage());
- }
+ // if Not delete
+ if (isDelete == 'N') {
+ return;
}
- private void deleteMember(){
- System.out.println("--------------------- Delete Member --------------------- \n");
-
- System.out.println("Plz enter the to-delete member id");
- int memberId = TSUtility.readInt();
-
- System.out.println("Confirm to Delete ? (Y/N)");
- char isDelete = TSUtility.readConfirmSelection();
-
- // if Not delete
- if (isDelete == 'N'){
- return;
- }
-
- // if delete
- try {
- teamSvc.removeMember(memberId);
- System.out.println("delete member OK!");
- } catch (TeamException e) {
- System.out.println("delete member failed!" + e.getMessage());
- }
- // back to the main program
- TSUtility.readReturn();
+ // if delete
+ try {
+ teamSvc.removeMember(memberId);
+ System.out.println("delete member OK!");
+ } catch (TeamException e) {
+ System.out.println("delete member failed!" + e.getMessage());
}
-}
\ No newline at end of file
+ // back to the main program
+ TSUtility.readReturn();
+ }
+}
diff --git a/src/main/java/Basics/EqualsDemo1/demo1.java b/src/main/java/Basics/EqualsDemo1/demo1.java
index 55b259b6..47a9c78f 100644
--- a/src/main/java/Basics/EqualsDemo1/demo1.java
+++ b/src/main/java/Basics/EqualsDemo1/demo1.java
@@ -56,8 +56,8 @@ public static void main(String[] args) {
System.out.println(cust1 == cust2); // FALSE
// example 5
- String str1 = new String("java");
- String str2 = new String("java");
+ String str1 = "java";
+ String str2 = "java";
System.out.println(
str1 == str2); // FALSE, same as above, str1 and str2 are in different address
}
diff --git a/src/main/java/Basics/EqualsDemo1/demo2.java b/src/main/java/Basics/EqualsDemo1/demo2.java
index 06b253b2..d460bdc7 100644
--- a/src/main/java/Basics/EqualsDemo1/demo2.java
+++ b/src/main/java/Basics/EqualsDemo1/demo2.java
@@ -46,8 +46,8 @@ public static void main(String[] args) {
System.out.println("==============");
// example 2
- String str1 = new String("java");
- String str2 = new String("java");
+ String str1 = "java";
+ String str2 = "java";
/**
* NOTE : the equals in String are actually overridden, -> so it is comparing the value, but
diff --git a/src/main/java/Basics/EqualsDemo4/test1.java b/src/main/java/Basics/EqualsDemo4/test1.java
index ed3fb90f..707ff9ca 100644
--- a/src/main/java/Basics/EqualsDemo4/test1.java
+++ b/src/main/java/Basics/EqualsDemo4/test1.java
@@ -30,8 +30,8 @@ public static void main(String[] args) {
}
class User {
- private int id;
- private String name;
+ private final int id;
+ private final String name;
public User(int id, String name) {
this.id = id;
diff --git a/src/main/java/Basics/ExceptionDemo1.java b/src/main/java/Basics/ExceptionDemo1.java
index 994e5b40..f7fbf11b 100644
--- a/src/main/java/Basics/ExceptionDemo1.java
+++ b/src/main/java/Basics/ExceptionDemo1.java
@@ -4,12 +4,11 @@
// https://www.youtube.com/watch?v=RXPAMZEYEi8&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=374
// https://www.youtube.com/watch?v=JBGh4Lb9Fns&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=380
-import org.junit.jupiter.api.Test;
-
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
+import org.junit.jupiter.api.Test;
/**
* Exception 1
diff --git a/src/main/java/Basics/ExceptionDemo2.java b/src/main/java/Basics/ExceptionDemo2.java
index 20db8a8d..61d7f80b 100644
--- a/src/main/java/Basics/ExceptionDemo2.java
+++ b/src/main/java/Basics/ExceptionDemo2.java
@@ -3,11 +3,10 @@
// https://www.youtube.com/watch?v=kA42AuUDWJY&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=374
// https://www.youtube.com/watch?v=u9Jz6ja8GiU&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=376
-import org.junit.jupiter.api.Test;
-
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
+import org.junit.jupiter.api.Test;
/**
* Exception 2 - finally using
diff --git a/src/main/java/Basics/ExceptionDemo3.java b/src/main/java/Basics/ExceptionDemo3.java
index 27fbcd44..8fd4611a 100644
--- a/src/main/java/Basics/ExceptionDemo3.java
+++ b/src/main/java/Basics/ExceptionDemo3.java
@@ -48,13 +48,13 @@ public static void main(String[] args) {
}
public static void method2()
- throws FileNotFoundException,
+ throws
IOException { // or throws IOException only, since IOException is FileNotFoundException's
- // superclass
+ // superclass
method1();
}
- public static void method1() throws FileNotFoundException, IOException {
+ public static void method1() throws IOException {
File file = new File("test.txt");
FileInputStream fis = new FileInputStream(file);
int data = fis.read();
diff --git a/src/main/java/Basics/ExceptionDemo4.java b/src/main/java/Basics/ExceptionDemo4.java
index b2e8f6b7..0140df69 100644
--- a/src/main/java/Basics/ExceptionDemo4.java
+++ b/src/main/java/Basics/ExceptionDemo4.java
@@ -26,13 +26,13 @@ public static void method3() {
}
public static void method2()
- throws FileNotFoundException,
+ throws
IOException { // or throws IOException only, since IOException is FileNotFoundException's
- // superclass
+ // superclass
method1();
}
- public static void method1() throws FileNotFoundException, IOException {
+ public static void method1() throws IOException {
File file = new File("test.txt");
FileInputStream fis = new FileInputStream(file);
int data = fis.read();
diff --git a/src/main/java/Basics/ExceptionDemo8.java b/src/main/java/Basics/ExceptionDemo8.java
index 783eea81..d493d0b9 100644
--- a/src/main/java/Basics/ExceptionDemo8.java
+++ b/src/main/java/Basics/ExceptionDemo8.java
@@ -11,11 +11,11 @@ public static void main(String[] args) {
*/
ReturnExceptionDemo returnExceptionDemo = new ReturnExceptionDemo();
try {
- returnExceptionDemo.methodA();
+ ReturnExceptionDemo.methodA();
} catch (Exception e) {
System.out.println(e.getMessage());
}
- returnExceptionDemo.methodB();
+ ReturnExceptionDemo.methodB();
}
}
diff --git a/src/main/java/Basics/GetterSetterDemo2.java b/src/main/java/Basics/GetterSetterDemo2.java
index 2de4ee73..2648f005 100644
--- a/src/main/java/Basics/GetterSetterDemo2.java
+++ b/src/main/java/Basics/GetterSetterDemo2.java
@@ -17,7 +17,7 @@ public static void main(String[] args) {
}
public static class Encrypt {
- private char[] cArray = new char[26];
+ private final char[] cArray = new char[26];
private int a;
private int b;
private int n;
diff --git a/src/main/java/Basics/HashMapDemo1.java b/src/main/java/Basics/HashMapDemo1.java
index b6d91ac6..031639fb 100644
--- a/src/main/java/Basics/HashMapDemo1.java
+++ b/src/main/java/Basics/HashMapDemo1.java
@@ -6,25 +6,25 @@
import java.util.Map;
public class HashMapDemo1 {
- public static void main(String[] args) {
+ public static void main(String[] args) {
- HashMap myHashMap = new HashMap(1, 1);
- System.out.println("myHashMap = " + myHashMap);
+ HashMap myHashMap = new HashMap(1, 1);
+ System.out.println("myHashMap = " + myHashMap);
- myHashMap.put("abc", 123);
+ myHashMap.put("abc", 123);
- System.out.println("myMap = " + myHashMap);
- System.out.println("keys =" + myHashMap.keySet());
- System.out.println("values =" + myHashMap.values());
+ System.out.println("myMap = " + myHashMap);
+ System.out.println("keys =" + myHashMap.keySet());
+ System.out.println("values =" + myHashMap.values());
- System.out.println("=======================");
+ System.out.println("=======================");
- Map myMap = new HashMap(1, 1);
- System.out.println("myMap = " + myMap);
+ Map myMap = new HashMap(1, 1);
+ System.out.println("myMap = " + myMap);
- myMap.put("abc", 123);
+ myMap.put("abc", 123);
- System.out.println("keys =" + myMap.keySet());
- System.out.println("values =" + myMap.values());
- }
+ System.out.println("keys =" + myMap.keySet());
+ System.out.println("values =" + myMap.values());
+ }
}
diff --git a/src/main/java/Basics/ImportDemo1.java b/src/main/java/Basics/ImportDemo1.java
index 1db4bd84..5a0f80d1 100644
--- a/src/main/java/Basics/ImportDemo1.java
+++ b/src/main/java/Basics/ImportDemo1.java
@@ -1,6 +1,5 @@
package Basics;
-
import java.util.Arrays;
// https://www.youtube.com/watch?v=0ErGo2Dj7lM&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=239
@@ -23,15 +22,15 @@
*/
public class ImportDemo1 {
- public static void main(String[] args){
- // run
- String info = Arrays.toString(new int[] {1,2,3});
+ public static void main(String[] args) {
+ // run
+ String info = Arrays.toString(new int[] {1, 2, 3});
- System.out.println("info = " + info);
+ System.out.println("info = " + info);
- // use class/interface with same name but from different package
- Basics.thisDemo5.Account acc1 = new Basics.thisDemo5.Account(1000);
+ // use class/interface with same name but from different package
+ Basics.thisDemo5.Account acc1 = new Basics.thisDemo5.Account(1000);
- Basics.thisDemo3.Account acc2 = new Basics.thisDemo3.Account(1, 100, 0.1);
- }
+ Basics.thisDemo3.Account acc2 = new Basics.thisDemo3.Account(1, 100, 0.1);
+ }
}
diff --git a/src/main/java/Basics/JUnit_1/JUnitTest.java b/src/main/java/Basics/JUnit_1/JUnitTest.java
index 9c54f5a0..23d28a0c 100644
--- a/src/main/java/Basics/JUnit_1/JUnitTest.java
+++ b/src/main/java/Basics/JUnit_1/JUnitTest.java
@@ -5,50 +5,47 @@
// https://www.youtube.com/watch?v=O1XnFHdsjYU&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=302
/**
- * JUnit unit test in Java
+ * JUnit unit test in Java
*
- * Steps :
+ * Steps :
*
- * 1) add library -> JUnit (JUnit4)
- * - for intelliJ : https://www.jetbrains.com/help/idea/library.html#lib_levels
+ *
1) add library -> JUnit (JUnit4) - for intelliJ :
+ * https://www.jetbrains.com/help/idea/library.html#lib_levels
*
- * 2) create a java class for unit test
- * - requirement of the java class
- * - 1. public class
- * - 2. offers a public non param constructor (use default is OK)
- * - 3. implement the unit test method in the class -> public method, NO param, and WITHOUT return value
+ *
2) create a java class for unit test - requirement of the java class - 1. public class - 2.
+ * offers a public non param constructor (use default is OK) - 3. implement the unit test method in
+ * the class -> public method, NO param, and WITHOUT return value
*
- * 3) need to add @Test over the test method, and import the corresponding library
+ *
3) need to add @Test over the test method, and import the corresponding library
*
- * 4) after creating the test method, write the test code
+ *
4) after creating the test method, write the test code
*
- * 5) after finishing the test code -> click "run JUnit test"
+ *
5) after finishing the test code -> click "run JUnit test"
*
- * 6) if there is no exception -> green
- * else -> red, and with error/exception msg
+ *
6) if there is no exception -> green else -> red, and with error/exception msg
*/
// class for unit test
public class JUnitTest {
- // test method
- @Test
- public void testEquals(){
- String s1 = "KK";
- String s2 = "KK";
-
- System.out.println(s1.equals(s2));
- }
-
-// @Test
-// public void testDownCasting(){
-// Object obj = new String ("XX");
-// Date date = (Date) obj;
-// }
-
- @Test
- public void testToString(){
- String s1 = "KK";
- System.out.println(s1.toString());
- }
+ // test method
+ @Test
+ public void testEquals() {
+ String s1 = "KK";
+ String s2 = "KK";
+
+ System.out.println(s1.equals(s2));
+ }
+
+ // @Test
+ // public void testDownCasting(){
+ // Object obj = new String ("XX");
+ // Date date = (Date) obj;
+ // }
+
+ @Test
+ public void testToString() {
+ String s1 = "KK";
+ System.out.println(s1);
+ }
}
diff --git a/src/main/java/Basics/Overloading1.java b/src/main/java/Basics/Overloading1.java
index 7aa39c29..9763cf1e 100644
--- a/src/main/java/Basics/Overloading1.java
+++ b/src/main/java/Basics/Overloading1.java
@@ -18,10 +18,8 @@ class OverloadingClass1 {
public String myPrint(String s) {
return "this is String print !!! " + s;
}
- ;
- public String myPrint(Integer i) {
+ public String myPrint(Integer i) {
return "this is Integer print !!! " + i.toString();
}
- ;
}
diff --git a/src/main/java/Basics/ProxyDemo1.java b/src/main/java/Basics/ProxyDemo1.java
index a2862f9d..406eda83 100644
--- a/src/main/java/Basics/ProxyDemo1.java
+++ b/src/main/java/Basics/ProxyDemo1.java
@@ -5,7 +5,7 @@
interface Network {
// attr
// method
- public void browse();
+ void browse();
}
/**
@@ -53,7 +53,7 @@ public void browse() {
/** proxy class */
class ProxyServer implements Network {
// attr
- private Network work;
+ private final Network work;
// constructor
public ProxyServer(Network work) {
diff --git a/src/main/java/Basics/ProxyDemo2.java b/src/main/java/Basics/ProxyDemo2.java
index be268d48..dec2ca64 100644
--- a/src/main/java/Basics/ProxyDemo2.java
+++ b/src/main/java/Basics/ProxyDemo2.java
@@ -54,7 +54,7 @@ public void collectMoney() {}
/** proxy class */
class Agent implements Star {
// attr
- private Star real;
+ private final Star real;
// constructor
public Agent(Star real) {
diff --git a/src/main/java/Basics/SingletonDemo1.java b/src/main/java/Basics/SingletonDemo1.java
index 84a0cb45..69cec3d8 100644
--- a/src/main/java/Basics/SingletonDemo1.java
+++ b/src/main/java/Basics/SingletonDemo1.java
@@ -23,8 +23,8 @@ public static void main(String[] args) {
// pros : Thread safety
// cons : could create a class, but not uses it -> resource wasting
class Single {
- private static Single s = new Single();
- ; // make constructor private
+ private static final Single s = new Single();
+ // make constructor private
public Single() {}
@@ -55,9 +55,8 @@ public static Single2 getInstance() {
// pros : 2. Thread safety (no interruption when running)
class Singleton {
private Singleton() {}
- ;
- // export below static method to public
+ // export below static method to public
public static Singleton getInstance() {
return SingltonInstance.INSTANCE;
}
diff --git a/src/main/java/Basics/SingletonDemo2.java b/src/main/java/Basics/SingletonDemo2.java
index a2eb92f9..03233312 100644
--- a/src/main/java/Basics/SingletonDemo2.java
+++ b/src/main/java/Basics/SingletonDemo2.java
@@ -19,7 +19,7 @@ public static void main(String[] args) {
// verify if b1, b2 are belong to same instance
System.out.println(b1.toString());
- System.out.println(b2.toString());
+ System.out.println(b2);
System.out.println(b1 == b2); // check if b1, b2 are in the same address
}
@@ -30,13 +30,14 @@ class Bank {
// step 2) create an "internal" class instance
// step 4) make below class as static
- private static Bank instance =
+ private static final Bank instance =
new Bank(); // *** MAIN DIFFERENCE WITHIN EAGER & LAZY initialization (eager : create
// step 1) private constructor
// constructor
private Bank() {}
- // directly)
+
+ // directly)
// step 3) offer public STATIC method that can return the class (we create above)
// -> reason why we use static here : we can't use getInstance without class, but we need
diff --git a/src/main/java/Basics/SingletonDemo3.java b/src/main/java/Basics/SingletonDemo3.java
index 31802351..1bf049ff 100644
--- a/src/main/java/Basics/SingletonDemo3.java
+++ b/src/main/java/Basics/SingletonDemo3.java
@@ -32,7 +32,8 @@ class Order2 {
// step 1) private constructor
// constructor
private Order2() {}
- // stage)
+
+ // stage)
// step 3) offer a public, static method that can return current class
public static Order2 getInstance() {
diff --git a/src/main/java/Basics/TimeZone/demo1.java b/src/main/java/Basics/TimeZone/demo1.java
index a8008a53..aaa52ea2 100644
--- a/src/main/java/Basics/TimeZone/demo1.java
+++ b/src/main/java/Basics/TimeZone/demo1.java
@@ -2,7 +2,6 @@
// https://mkyong.com/java/java-display-list-of-timezone-with-gmt/
-import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.TimeZone;
@@ -13,8 +12,7 @@ public class demo1 {
public static void main(String[] args) {
String[] ids = TimeZone.getAvailableIDs();
- ;
- Set hash_Set = new HashSet();
+ Set hash_Set = new HashSet();
for (String id : ids) {
diff --git a/src/main/java/Basics/ToString_1.java b/src/main/java/Basics/ToString_1.java
index 972330ff..4d1dd2f8 100644
--- a/src/main/java/Basics/ToString_1.java
+++ b/src/main/java/Basics/ToString_1.java
@@ -23,12 +23,12 @@ public static void main(String[] args) {
// example 1
CustomerX cust1 = new CustomerX("JIM", 19);
System.out.println(cust1); // Basics.CustomerX@33c7353a (before rewrite toString)
- System.out.println(cust1.toString()); // Basics.CustomerX@33c7353a (before rewrite toString)
+ System.out.println(cust1); // Basics.CustomerX@33c7353a (before rewrite toString)
System.out.println("=====================");
// example 2
- String str1 = new String("USA");
+ String str1 = "USA";
System.out.println(str1);
System.out.println("=====================");
@@ -36,14 +36,14 @@ public static void main(String[] args) {
// example 3
Date date1 = new Date(23534534534L);
System.out.println(date1);
- System.out.println(date1.toString());
+ System.out.println(date1);
}
}
class CustomerX {
// attr
- private String name;
- private int id;
+ private final String name;
+ private final int id;
// constructor
public CustomerX(String name, int id) {
diff --git a/src/main/java/Basics/WrapperDemo1/WrapperTest.java b/src/main/java/Basics/WrapperDemo1/WrapperTest.java
index 1a341f97..408d0228 100644
--- a/src/main/java/Basics/WrapperDemo1/WrapperTest.java
+++ b/src/main/java/Basics/WrapperDemo1/WrapperTest.java
@@ -17,17 +17,17 @@ public void test1() {
int num1 = 10;
// System.out.println(num1.toString()); // this one is not correct
Integer in1 = new Integer(num1);
- System.out.println(in1.toString());
+ System.out.println(in1);
// this one is also OK
Integer in2 = new Integer("123");
- System.out.println(in2.toString());
+ System.out.println(in2);
Float f1 = new Float(12.3f);
- System.out.println(f1.toString());
+ System.out.println(f1);
Float f2 = new Float("12.3");
- System.out.println(f2.toString());
+ System.out.println(f2);
Boolean b1 = new Boolean(true);
Boolean b2 = new Boolean("true");
diff --git a/src/main/java/Basics/WrapperDemo1/WrapperTest3.java b/src/main/java/Basics/WrapperDemo1/WrapperTest3.java
index 4130b345..2dcb71e6 100644
--- a/src/main/java/Basics/WrapperDemo1/WrapperTest3.java
+++ b/src/main/java/Basics/WrapperDemo1/WrapperTest3.java
@@ -15,9 +15,12 @@ public class WrapperTest3 {
/** autoboxing */
int num2 = 10;
+
Integer in1 = num2;
+
/** unboxing */
int num3 = in1;
+
boolean b1 = true;
Boolean b2 = b1;
boolean b3 = b2;
diff --git a/src/main/java/Basics/forLoop2.java b/src/main/java/Basics/forLoop2.java
index e480a52c..0abf0a15 100644
--- a/src/main/java/Basics/forLoop2.java
+++ b/src/main/java/Basics/forLoop2.java
@@ -1,36 +1,35 @@
package Basics;
/** for loop demo 2 : ArrayList */
-
import java.util.ArrayList;
import java.util.Iterator;
public class forLoop2 {
- public static void main(String[] args) {
- ArrayList col1 = new ArrayList();
+ public static void main(String[] args) {
+ ArrayList col1 = new ArrayList();
- col1.add(123);
- col1.add(456);
- col1.add("abc");
+ col1.add(123);
+ col1.add(456);
+ col1.add("abc");
- /** for loop method 1 : basic */
- for (int i=0; i < col1.toArray().length; i++){
- System.out.println(col1.toArray()[i]);
- }
+ /** for loop method 1 : basic */
+ for (int i = 0; i < col1.toArray().length; i++) {
+ System.out.println(col1.toArray()[i]);
+ }
- System.out.println("================");
+ System.out.println("================");
- /** for loop method 2 : enhanced for loop */
- for (Object o : col1){
- System.out.println(o);
- }
+ /** for loop method 2 : enhanced for loop */
+ for (Object o : col1) {
+ System.out.println(o);
+ }
- System.out.println("================");
+ System.out.println("================");
- /** for loop method 3: iterator */
- Iterator iterator = col1.iterator();
- while (iterator.hasNext()){
- System.out.println(iterator.next());
- }
+ /** for loop method 3: iterator */
+ Iterator iterator = col1.iterator();
+ while (iterator.hasNext()) {
+ System.out.println(iterator.next());
}
+ }
}
diff --git a/src/main/java/Basics/interfaceDemo1.java b/src/main/java/Basics/interfaceDemo1.java
index a8086853..cd37ef72 100644
--- a/src/main/java/Basics/interfaceDemo1.java
+++ b/src/main/java/Basics/interfaceDemo1.java
@@ -6,13 +6,13 @@ interface Flyable {
// attr
// global constant
- public static final int MAX_SPEED = 100;
+ int MAX_SPEED = 100;
// public static final int MIN_SPEED = 1;
// or, can write as below
int MIN_SPEED = 1; // omit public static final
// method
- public abstract void fly();
+ void fly();
void stop(); // omit public abstract
}
diff --git a/src/main/java/Basics/interfaceDemo2.java b/src/main/java/Basics/interfaceDemo2.java
index 4f2900dc..91f9b280 100644
--- a/src/main/java/Basics/interfaceDemo2.java
+++ b/src/main/java/Basics/interfaceDemo2.java
@@ -3,160 +3,129 @@
// https://www.youtube.com/watch?v=qXb8Z9cjcDk&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=351
// https://www.youtube.com/watch?v=rM2f0mTie_Q&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=352
-interface Flyable2{
+interface Flyable2 {
- // attr
- // global constant
- public static final int MAX_SPEED = 100;
- //public static final int MIN_SPEED = 1;
- // or, can write as below
- int MIN_SPEED = 1; // omit public static final
+ // attr
+ // global constant
+ int MAX_SPEED = 100;
+ // public static final int MIN_SPEED = 1;
+ // or, can write as below
+ int MIN_SPEED = 1; // omit public static final
- // method
- public abstract void fly();
+ // method
+ void fly();
- void stop(); // omit public abstract
+ void stop(); // omit public abstract
}
-interface Attackable2{
- void attack();
+interface Attackable2 {
+ void attack();
}
-interface AA_{
- void method1();
+interface AA_ {
+ void method1();
}
-
interface BB_ {
- void method2();
+ void method2();
}
// interface's multiple inheritance
-interface CC_ extends AA_, BB_{
-
-}
+interface CC_ extends AA_, BB_ {}
/**
- * Interface part 2
- *
- * 1) use keyword "interface"
- * 2) in java, interface, and class are the structure in the same level
- * 3) how to define interface ? elements inside interface ?
- * 3.1) JDK 7 and before
- * -> can ONLY use global constant and abstract method
- * -> global constant : public static final (public static final can be omitted)
- * -> abstract method : public abstract (public abstract can be omitted)
- * 3.2) JDK 8 and after
- * -> can HAVE global constant, abstract method, static method, default method
+ * Interface part 2
*
- * 4) CAN NOT define constructor in interface
- * -> interface CAN NOT be instantiated
+ * 1) use keyword "interface" 2) in java, interface, and class are the structure in the same
+ * level 3) how to define interface ? elements inside interface ? 3.1) JDK 7 and before -> can ONLY
+ * use global constant and abstract method -> global constant : public static final (public static
+ * final can be omitted) -> abstract method : public abstract (public abstract can be omitted) 3.2)
+ * JDK 8 and after -> can HAVE global constant, abstract method, static method, default method
*
- * 5) in java, we usually use CLASS to "implement" interface (not extend)
- * -> if class implements all abstract methods in interface -> this class can be instantiated
- * -> if class NOT implement all abstract methods in interface -> this class CAN NOT be instantiated
+ *
4) CAN NOT define constructor in interface -> interface CAN NOT be instantiated
*
- * 6) in Java, we can implement multiple interfaces -> complement that java only have SINGLE inheritance
- * -> class Bullet implements Flyable, Attackable (check below)
- * -> pattern : class AA extends BB implement CC, DD, EE (inheritance -> implementation)
+ *
5) in java, we usually use CLASS to "implement" interface (not extend) -> if class implements
+ * all abstract methods in interface -> this class can be instantiated -> if class NOT implement all
+ * abstract methods in interface -> this class CAN NOT be instantiated
*
- * 7) relationships
+ *
6) in Java, we can implement multiple interfaces -> complement that java only have SINGLE
+ * inheritance -> class Bullet implements Flyable, Attackable (check below) -> pattern : class AA
+ * extends BB implement CC, DD, EE (inheritance -> implementation)
*
- * 7.1) interface ----implementation --> class
- * 7.2) class ----inheritance --> class
- * 7.3) interface ----inheritance --> interface
- * -> example : interface CC_ extends AA_, BB
+ *
7) relationships
*
- * 8) interface uses the mindset of polymorphism
+ *
7.1) interface ----implementation --> class 7.2) class ----inheritance --> class 7.3)
+ * interface ----inheritance --> interface -> example : interface CC_ extends AA_, BB
*
- * 9) interface is like a "rule", "standard", "format"
- * -> that everyone needs to follow
- * -> (implemented by class)
+ *
8) interface uses the mindset of polymorphism
*
- * 10) interface VS abstract class ?
+ *
9) interface is like a "rule", "standard", "format" -> that everyone needs to follow ->
+ * (implemented by class)
*
+ *
10) interface VS abstract class ?
*/
-
public class interfaceDemo2 {
- public static void main(String[] args) {
- // run
- System.out.println(Flyable2.MAX_SPEED);
- System.out.println(Flyable2.MIN_SPEED);
+ public static void main(String[] args) {
+ // run
+ System.out.println(Flyable2.MAX_SPEED);
+ System.out.println(Flyable2.MIN_SPEED);
- // Cannot assign a value to final variable 'MIN_SPEED'
- //Flyable.MIN_SPEED = 999;
+ // Cannot assign a value to final variable 'MIN_SPEED'
+ // Flyable.MIN_SPEED = 999;
- System.out.println("==============");
+ System.out.println("==============");
- Plane2 p1 = new Plane2();
- p1.fly();
- p1.stop();
- }
+ Plane2 p1 = new Plane2();
+ p1.fly();
+ p1.stop();
+ }
}
-class Plane2 implements Flyable2{
+class Plane2 implements Flyable2 {
- @Override
- public void fly() {
- System.out.println("plane can fly !!!");
- }
+ @Override
+ public void fly() {
+ System.out.println("plane can fly !!!");
+ }
- @Override
- public void stop() {
- System.out.println("plane can stop !!!");
- }
+ @Override
+ public void stop() {
+ System.out.println("plane can stop !!!");
+ }
}
-abstract class Kite2 implements Flyable2{
-
- @Override
- public void fly() {
+abstract class Kite2 implements Flyable2 {
- }
+ @Override
+ public void fly() {}
}
-class Bullet2 implements Flyable2, Attackable2{
-
- @Override
- public void attack() {
-
- }
+class Bullet2 implements Flyable2, Attackable2 {
- @Override
- public void fly() {
+ @Override
+ public void attack() {}
- }
+ @Override
+ public void fly() {}
- @Override
- public void stop() {
-
- }
+ @Override
+ public void stop() {}
}
class Bullet3 extends Object implements Flyable2, Attackable2, CC_ {
- @Override
- public void fly() {
-
- }
-
- @Override
- public void stop() {
-
- }
+ @Override
+ public void fly() {}
- @Override
- public void attack() {
+ @Override
+ public void stop() {}
- }
+ @Override
+ public void attack() {}
- @Override
- public void method1() {
+ @Override
+ public void method1() {}
- }
-
- @Override
- public void method2() {
-
- }
-}
\ No newline at end of file
+ @Override
+ public void method2() {}
+}
diff --git a/src/main/java/Basics/interfaceDemo4/CompareObject.java b/src/main/java/Basics/interfaceDemo4/CompareObject.java
index 0e98de32..20609218 100644
--- a/src/main/java/Basics/interfaceDemo4/CompareObject.java
+++ b/src/main/java/Basics/interfaceDemo4/CompareObject.java
@@ -4,5 +4,5 @@
public interface CompareObject {
// if 0 -> equals, if positive -> current value is larger, if minus -> current value is smaller
- public int compareTo(Object o);
+ int compareTo(Object o);
}
diff --git a/src/main/java/Basics/interfaceDemo5/CompareObject.java b/src/main/java/Basics/interfaceDemo5/CompareObject.java
index 110c41cd..6b081779 100644
--- a/src/main/java/Basics/interfaceDemo5/CompareObject.java
+++ b/src/main/java/Basics/interfaceDemo5/CompareObject.java
@@ -4,5 +4,5 @@
public interface CompareObject {
// if 0 -> equals, if positive -> current value is larger, if minus -> current value is smaller
- public int compareTo(Object o);
+ int compareTo(Object o);
}
diff --git a/src/main/java/Basics/interfaceDemo5/test.java b/src/main/java/Basics/interfaceDemo5/test.java
index f0d476fd..f4f3d646 100644
--- a/src/main/java/Basics/interfaceDemo5/test.java
+++ b/src/main/java/Basics/interfaceDemo5/test.java
@@ -20,7 +20,7 @@ public static void main(String[] args) {
System.out.println("==================");
- int compareValue2 = c1.compareTo(new String("ss"));
+ int compareValue2 = c1.compareTo("ss");
System.out.println("compareValue2 = " + compareValue2);
}
}
diff --git a/src/main/java/Basics/interfaceDemo6/CompareA.java b/src/main/java/Basics/interfaceDemo6/CompareA.java
index c668d1f7..7e6133e8 100644
--- a/src/main/java/Basics/interfaceDemo6/CompareA.java
+++ b/src/main/java/Basics/interfaceDemo6/CompareA.java
@@ -11,12 +11,12 @@
public interface CompareA {
// static method
- public static void method1() {
+ static void method1() {
System.out.println("Compare A : N.Y.");
}
// default method
- public default void method2() {
+ default void method2() {
System.out.println("Compare A : C.A.");
}
diff --git a/src/main/java/Basics/objectDemo1/GCdemo1.java b/src/main/java/Basics/objectDemo1/GCdemo1.java
index b8324e7b..19188fdb 100644
--- a/src/main/java/Basics/objectDemo1/GCdemo1.java
+++ b/src/main/java/Basics/objectDemo1/GCdemo1.java
@@ -7,7 +7,7 @@ public static void main(String[] args) {
// run
User u1 = new User("001", 19);
- System.out.println(u1.toString());
+ System.out.println(u1);
System.out.println(u1);
diff --git a/src/main/java/Basics/objectDemo2/testCircle.java b/src/main/java/Basics/objectDemo2/testCircle.java
index 10dcb099..89158eb8 100644
--- a/src/main/java/Basics/objectDemo2/testCircle.java
+++ b/src/main/java/Basics/objectDemo2/testCircle.java
@@ -2,7 +2,6 @@
// https://www.youtube.com/watch?v=yHBFLvnIM4E&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=301
-import java.util.Currency;
public class testCircle {
@@ -10,7 +9,7 @@ public static void main(String[] args) {
Circle c1 = new Circle(2.9);
Circle c2 = new Circle(2.9);
Circle c3 = new Circle(2.9, "blu", 2.0);
- Circle c4 = new Circle(3, new String("black"), 3.0);
+ Circle c4 = new Circle(3, "black", 3.0);
// check if circle are the same
// Note : use equals for reference type comparision
@@ -18,7 +17,7 @@ public static void main(String[] args) {
System.out.println("Check if radius same : " + c1.equals(c2));
- System.out.println("Print circle as string : " + c1.toString());
+ System.out.println("Print circle as string : " + c1);
System.out.println("Print circle as string : " + c3);
}
}
diff --git a/src/main/java/Basics/polymorphism_2/OrderTest.java b/src/main/java/Basics/polymorphism_2/OrderTest.java
index f845f571..04d92547 100644
--- a/src/main/java/Basics/polymorphism_2/OrderTest.java
+++ b/src/main/java/Basics/polymorphism_2/OrderTest.java
@@ -15,10 +15,9 @@ public void method(Object obj) { // can use any subclass of Object with polymorp
class Driver {
// example 2
public void getData(
- Connection
- conn) { // Connection is the superclass (interface), but when runtime, it will use
- // different conn (subclass), e.g. : mysqlConn, postgreConn... ( polymorphism
- // feature)
+ Connection conn) { // Connection is the superclass (interface), but when runtime, it will use
+ // different conn (subclass), e.g. : mysqlConn, postgreConn... ( polymorphism
+ // feature)
// conn.method1();
// conn.method2();
// ....
diff --git a/src/main/java/Basics/staticDemo3.java b/src/main/java/Basics/staticDemo3.java
index f22c2e63..3d4b3c08 100644
--- a/src/main/java/Basics/staticDemo3.java
+++ b/src/main/java/Basics/staticDemo3.java
@@ -8,7 +8,7 @@ public static void main(String[] args) {
Japanese j1 = new Japanese();
j1.name = "yoshi";
j1.age = 19;
- j1.nation = "JP";
+ Japanese.nation = "JP";
Japanese j2 = new Japanese();
j2.name = "Lynn";
@@ -17,11 +17,11 @@ public static void main(String[] args) {
// nation is static attr
// so there is ONLY ONE such value in the "static area"
// and j1 already define nation
- System.out.println("j2.nation = " + j2.nation);
+ System.out.println("j2.nation = " + Japanese.nation);
- j2.nation = "Japan";
+ Japanese.nation = "Japan";
- System.out.println("j1.nation = " + j1.nation);
+ System.out.println("j1.nation = " + Japanese.nation);
// and we can call the static method directly
System.out.println(Japanese.nation);
diff --git a/src/main/java/Basics/staticDemo5.java b/src/main/java/Basics/staticDemo5.java
index 4810a06a..b5162409 100644
--- a/src/main/java/Basics/staticDemo5.java
+++ b/src/main/java/Basics/staticDemo5.java
@@ -2,89 +2,85 @@
// https://www.youtube.com/watch?v=U_ho3BRDwsE&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=321
-
-/**
- * static attr can be shared by ALL instances
- */
-
+/** static attr can be shared by ALL instances */
public class staticDemo5 {
- public static void main(String[] args) {
+ public static void main(String[] args) {
- // run
- Circle c1 = new Circle();
- Circle c2 = new Circle();
+ // run
+ Circle c1 = new Circle();
+ Circle c2 = new Circle();
- System.out.println("c1.id = " + c1.getId()); // 1001
- System.out.println("c2.id = " + c2.getId()); // 1002
+ System.out.println("c1.id = " + c1.getId()); // 1001
+ System.out.println("c2.id = " + c2.getId()); // 1002
- System.out.println("total instances = " + Circle.getTotal());
+ System.out.println("total instances = " + Circle.getTotal());
- Circle c3 = new Circle();
+ Circle c3 = new Circle();
- System.out.println("total instances = " + Circle.getTotal());
+ System.out.println("total instances = " + Circle.getTotal());
- Circle c4 = new Circle(9.99);
- System.out.println("c4's area = " + c4.findArea());
+ Circle c4 = new Circle(9.99);
+ System.out.println("c4's area = " + c4.findArea());
- System.out.println("total instances = " + Circle.getTotal());
- }
+ System.out.println("total instances = " + Circle.getTotal());
+ }
}
-class Circle{
- // static attr
- private static int total; // how many instances created
- private static int init = 1001; // multiple instances share this attr
- // attr
- private double radius;
- private int id;
-
- // constructor
- public Circle(){
- // first time : 1001
- // second time : 1002
- // ....
- id = init++;
-
- // first time : 0
- // second time : 1
- // ....
- total++;
- }
-
- public Circle(double radius){
- // don't forget below
- // V1
- //this();
- // V2
- id = id++;
- total++;
- this.radius = radius;
- }
-
- /** Note : getter for total is static method (since total is static attr) */
- public static int getTotal() {
- return total;
- }
-
- public double getRadius() {
- return radius;
- }
-
- // getter, setter
- public void setRadius(double radius) {
- this.radius = radius;
- }
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- // method
- public double findArea(){
- return 3.14 * radius * radius;
- }
+class Circle {
+ // static attr
+ private static int total; // how many instances created
+ private static int init = 1001; // multiple instances share this attr
+ // attr
+ private double radius;
+ private int id;
+
+ // constructor
+ public Circle() {
+ // first time : 1001
+ // second time : 1002
+ // ....
+ id = init++;
+
+ // first time : 0
+ // second time : 1
+ // ....
+ total++;
+ }
+
+ public Circle(double radius) {
+ // don't forget below
+ // V1
+ // this();
+ // V2
+ id = id++;
+ total++;
+ this.radius = radius;
+ }
+
+ /** Note : getter for total is static method (since total is static attr) */
+ public static int getTotal() {
+ return total;
+ }
+
+ public double getRadius() {
+ return radius;
+ }
+
+ // getter, setter
+ public void setRadius(double radius) {
+ this.radius = radius;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ // method
+ public double findArea() {
+ return 3.14 * radius * radius;
+ }
}
diff --git a/src/main/java/Basics/staticDemo6/Account.java b/src/main/java/Basics/staticDemo6/Account.java
index e908dccc..a465ad37 100644
--- a/src/main/java/Basics/staticDemo6/Account.java
+++ b/src/main/java/Basics/staticDemo6/Account.java
@@ -7,7 +7,7 @@ public class Account {
private static double minBalance = 1.0;
private static int init = 1001; // for id
// attr
- private int id;
+ private final int id;
private String pwd = "0000"; // init with 0000
private double balance;
diff --git a/src/main/java/Basics/staticDemo6/test.java b/src/main/java/Basics/staticDemo6/test.java
index fe6cb887..dc05178b 100644
--- a/src/main/java/Basics/staticDemo6/test.java
+++ b/src/main/java/Basics/staticDemo6/test.java
@@ -10,13 +10,13 @@ public static void main(String[] args) {
Account a2 = new Account("123", 100);
- System.out.println(a1.toString());
- System.out.println(a2.toString());
+ System.out.println(a1);
+ System.out.println(a2);
Account.setInterestRate(0.38);
Account a3 = new Account();
- System.out.println(a3.getInterestRate());
- System.out.println(a3.toString());
+ System.out.println(Account.getInterestRate());
+ System.out.println(a3);
}
}
diff --git a/src/main/java/Basics/thisDemo2.java b/src/main/java/Basics/thisDemo2.java
index d2484613..cae85cc2 100644
--- a/src/main/java/Basics/thisDemo2.java
+++ b/src/main/java/Basics/thisDemo2.java
@@ -3,7 +3,7 @@
// https://www.youtube.com/watch?v=Pmqp7R-J3ys&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=232
public class thisDemo2 {
- public static void main(String args[]) {
+ public static void main(String[] args) {
// run
Person_4 p1 = new Person_4();
p1.setAge(100);
diff --git a/src/main/java/Basics/thisDemo3/Account.java b/src/main/java/Basics/thisDemo3/Account.java
index efe72c95..9ce53520 100644
--- a/src/main/java/Basics/thisDemo3/Account.java
+++ b/src/main/java/Basics/thisDemo3/Account.java
@@ -3,57 +3,57 @@
// https://www.youtube.com/watch?v=lc-IoBqYTTs&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=235
public class Account {
- // attr
- private int id;
- private double balance;
- private double annualInterestRate;
-
- // constructor
- public Account(int id, double balance, double annualInterestRate){
- this.id = id;
- this.balance = balance;
- this.annualInterestRate = annualInterestRate;
- }
-
- public int getId() {
- return id;
- }
-
- // getter, setter
- public void setId(int id) {
- this.id = id;
- }
-
- public double getBalance() {
- return balance;
- }
-
- public void setBalance(double balance) {
- this.balance = balance;
- }
-
- public double getAnnualInterestRate() {
- return annualInterestRate;
- }
-
- public void setAnnualInterestRate(double annualInterestRate) {
- this.annualInterestRate = annualInterestRate;
- }
-
- // method
- public void withDraw(double amount){ // get money
- if (balance < amount){
- System.out.println("WithDraw failed : balance is not enough!");
- return;
- }
- balance -= amount;
- System.out.println("WithDraw OK : get " + amount);
- }
-
- public void deposit(double amount){ // save money
- if (amount > 0){
- balance += amount;
- System.out.println("Deposit OK : get " + amount);
- }
- }
+ // attr
+ private int id;
+ private double balance;
+ private double annualInterestRate;
+
+ // constructor
+ public Account(int id, double balance, double annualInterestRate) {
+ this.id = id;
+ this.balance = balance;
+ this.annualInterestRate = annualInterestRate;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ // getter, setter
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public double getBalance() {
+ return balance;
+ }
+
+ public void setBalance(double balance) {
+ this.balance = balance;
+ }
+
+ public double getAnnualInterestRate() {
+ return annualInterestRate;
+ }
+
+ public void setAnnualInterestRate(double annualInterestRate) {
+ this.annualInterestRate = annualInterestRate;
+ }
+
+ // method
+ public void withDraw(double amount) { // get money
+ if (balance < amount) {
+ System.out.println("WithDraw failed : balance is not enough!");
+ return;
+ }
+ balance -= amount;
+ System.out.println("WithDraw OK : get " + amount);
+ }
+
+ public void deposit(double amount) { // save money
+ if (amount > 0) {
+ balance += amount;
+ System.out.println("Deposit OK : get " + amount);
+ }
+ }
}
diff --git a/src/main/java/Basics/thisDemo3/Customer.java b/src/main/java/Basics/thisDemo3/Customer.java
index ff73717e..7277c203 100644
--- a/src/main/java/Basics/thisDemo3/Customer.java
+++ b/src/main/java/Basics/thisDemo3/Customer.java
@@ -4,8 +4,8 @@
public class Customer {
// attr
- private String firstName;
- private String lastName;
+ private final String firstName;
+ private final String lastName;
private Account account; // from AccountDemo1.java (class type = Account)
// constructor
diff --git a/src/main/java/Basics/thisDemo5/Bank.java b/src/main/java/Basics/thisDemo5/Bank.java
index 072c11f5..dd00e256 100644
--- a/src/main/java/Basics/thisDemo5/Bank.java
+++ b/src/main/java/Basics/thisDemo5/Bank.java
@@ -5,7 +5,7 @@
public class Bank {
// attr
- private Customer[] customers; // an array can save multiple customers inside
+ private final Customer[] customers; // an array can save multiple customers inside
private int numberOfCustomers; // record customer count
// constructor
diff --git a/src/main/java/Basics/thisDemo5/Customer.java b/src/main/java/Basics/thisDemo5/Customer.java
index 39b22392..d44f5b05 100644
--- a/src/main/java/Basics/thisDemo5/Customer.java
+++ b/src/main/java/Basics/thisDemo5/Customer.java
@@ -5,8 +5,8 @@
public class Customer {
// attr
- private String firstName;
- private String lastName;
+ private final String firstName;
+ private final String lastName;
private Account account;
// constructor
diff --git a/src/main/java/Basics/valueTransfer1.java b/src/main/java/Basics/valueTransfer1.java
index eeb1e52b..d3d28f4c 100644
--- a/src/main/java/Basics/valueTransfer1.java
+++ b/src/main/java/Basics/valueTransfer1.java
@@ -2,7 +2,6 @@
// plz compare with valueTransfer2
-import java.util.Arrays;
public class valueTransfer1 {
public static void main(String[] args) {
@@ -25,7 +24,7 @@ public static void main(String[] args) {
System.out.println("--------------");
- int arr[] = {1, 3};
+ int[] arr = {1, 3};
test.swap_1_fixed(arr);
for (int j = 0; j < arr.length; j++) {
System.out.println(arr[j]);
diff --git a/src/main/java/DesignPattern/Builder/demo1.java b/src/main/java/DesignPattern/Builder/demo1.java
index 55a2117e..f3fabe41 100644
--- a/src/main/java/DesignPattern/Builder/demo1.java
+++ b/src/main/java/DesignPattern/Builder/demo1.java
@@ -24,15 +24,15 @@
*
關鍵程式碼:建造者:創建和提供實例,導演:管理建造出來的實例的依賴關係。
*/
interface Item {
- public String name();
+ String name();
- public Packing packing();
+ Packing packing();
- public float price();
+ float price();
}
interface Packing {
- public String pack();
+ String pack();
}
class Wrapper implements Packing {
@@ -119,7 +119,7 @@ public float price() {
class Meal {
// attr
- private List- items = new ArrayList<>();
+ private final List
- items = new ArrayList<>();
// method
void addItem(Item item) {
diff --git a/src/main/java/DesignPattern/Factory/demo1.java b/src/main/java/DesignPattern/Factory/demo1.java
index d89a0c94..d47a5139 100644
--- a/src/main/java/DesignPattern/Factory/demo1.java
+++ b/src/main/java/DesignPattern/Factory/demo1.java
@@ -64,7 +64,7 @@ public void drive() {
class CarFactory {
// attr
- private Vehicle vehicle;
+ private final Vehicle vehicle;
// constructor
public CarFactory(Vehicle vehicle) {
diff --git a/src/main/java/DesignPattern/Singleton/Hungry.java b/src/main/java/DesignPattern/Singleton/Hungry.java
index 86053635..c20876f9 100644
--- a/src/main/java/DesignPattern/Singleton/Hungry.java
+++ b/src/main/java/DesignPattern/Singleton/Hungry.java
@@ -33,7 +33,7 @@
class MyClass {
// attr
- private static MyClass instance = new MyClass();
+ private static final MyClass instance = new MyClass();
// constructor
// below is WRONG
diff --git a/src/main/java/Others/FreeMarker/demo1.java b/src/main/java/Others/FreeMarker/demo1.java
index 097dc9f8..fcfdcd6f 100644
--- a/src/main/java/Others/FreeMarker/demo1.java
+++ b/src/main/java/Others/FreeMarker/demo1.java
@@ -6,11 +6,9 @@
import Others.FreeMarker.bean.Book;
import Others.FreeMarker.bean.User;
import Others.FreeMarker.bean.User2;
-
import Others.FreeMarker.utls.FileUtil;
-import org.junit.jupiter.api.Test;
-
-import java.io.FileWriter;
+import freemarker.template.Configuration;
+import freemarker.template.TemplateException;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Path;
@@ -18,9 +16,7 @@
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-
-import freemarker.template.Configuration;
-import freemarker.template.TemplateException;
+import org.junit.jupiter.api.Test;
public class demo1 {
diff --git a/src/main/java/Workspace/workspace3.java b/src/main/java/Workspace/workspace3.java
index 73c97370..0bd3be75 100644
--- a/src/main/java/Workspace/workspace3.java
+++ b/src/main/java/Workspace/workspace3.java
@@ -1,8 +1,5 @@
package Workspace;
-import java.lang.management.ManagementFactory;
-import java.lang.management.ThreadInfo;
-import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.List;
diff --git a/src/main/java/dev/ArrayTest.java b/src/main/java/dev/ArrayTest.java
index 49629386..48d0d216 100644
--- a/src/main/java/dev/ArrayTest.java
+++ b/src/main/java/dev/ArrayTest.java
@@ -2,7 +2,6 @@
import dev.bean.Car;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
diff --git a/src/main/java/dev/CSV2Json.java b/src/main/java/dev/CSV2Json.java
index edc7ad9b..c919da25 100644
--- a/src/main/java/dev/CSV2Json.java
+++ b/src/main/java/dev/CSV2Json.java
@@ -1,13 +1,12 @@
package dev;
+import com.fasterxml.jackson.databind.*;
+import com.fasterxml.jackson.dataformat.csv.*;
+import dev.bean.Sales;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
-
-import com.fasterxml.jackson.databind.*;
-import com.fasterxml.jackson.dataformat.csv.*;
-import dev.bean.Sales;
import org.junit.jupiter.api.Test;
public class CSV2Json {
diff --git a/src/main/java/dev/CustomSortingTest.java b/src/main/java/dev/CustomSortingTest.java
index d7b091d8..84f0112f 100644
--- a/src/main/java/dev/CustomSortingTest.java
+++ b/src/main/java/dev/CustomSortingTest.java
@@ -8,208 +8,201 @@
import java.util.List;
import org.junit.jupiter.api.Test;
-/**
- *
- * https://segmentfault.com/q/1010000041496148
- * https://www.jianshu.com/p/5a3361959ae7
- */
-
+/** https://segmentfault.com/q/1010000041496148 https://www.jianshu.com/p/5a3361959ae7 */
public class CustomSortingTest {
- @Test
- public void test1(){
-
- Data d1 = new Data("1",null,null);
- Data d2 = new Data("2",null,null);
- Data d3 = new Data("3",null,null);
-
- Data[] dataList = new Data[]{d1,d3,d2};
+ @Test
+ public void test1() {
- Arrays.stream(dataList).forEach(System.out::println);
+ Data d1 = new Data("1", null, null);
+ Data d2 = new Data("2", null, null);
+ Data d3 = new Data("3", null, null);
- // NOTE : in order to use Arrays.sort, we HAVE to implement compareTom method in data bean first
- Arrays.sort(dataList);
+ Data[] dataList = new Data[] {d1, d3, d2};
- System.out.println();
+ Arrays.stream(dataList).forEach(System.out::println);
- Arrays.stream(dataList).forEach(System.out::println);
- }
+ // NOTE : in order to use Arrays.sort, we HAVE to implement compareTom method in data bean first
+ Arrays.sort(dataList);
- @Test
- public void test2(){
+ System.out.println();
- Data d1 = new Data("1","123",null);
- Data d2 = new Data("2","456",null);
- Data d3 = new Data("3","others",null);
- Data d4 = new Data("4","898",null);
+ Arrays.stream(dataList).forEach(System.out::println);
+ }
- //Data[] dataList = new Data[]{d1,d4,d3,d2};
- //List dataList = Arrays.asList(d3, d1, d4, d2);
- //List dataList = Arrays.asList(d1,d3,d2);
- Data[] dataList = new Data[]{d1,d3,d2,d4};
+ @Test
+ public void test2() {
- Arrays.stream(dataList).forEach(System.out::println);
+ Data d1 = new Data("1", "123", null);
+ Data d2 = new Data("2", "456", null);
+ Data d3 = new Data("3", "others", null);
+ Data d4 = new Data("4", "898", null);
- System.out.println();
+ // Data[] dataList = new Data[]{d1,d4,d3,d2};
+ // List dataList = Arrays.asList(d3, d1, d4, d2);
+ // List dataList = Arrays.asList(d1,d3,d2);
+ Data[] dataList = new Data[] {d1, d3, d2, d4};
- // NOTE : in order to use Arrays.sort, we HAVE to implement compareTom method in data bean first
-// dataList.remove(idx);
-// dataList.forEach(System.out::println);
- Arrays.sort(dataList);
+ Arrays.stream(dataList).forEach(System.out::println);
- System.out.println();
+ System.out.println();
- Arrays.stream(dataList).forEach(System.out::println);
- }
+ // NOTE : in order to use Arrays.sort, we HAVE to implement compareTom method in data bean first
+ // dataList.remove(idx);
+ // dataList.forEach(System.out::println);
+ Arrays.sort(dataList);
+ System.out.println();
- @Test
- public void test2_x(){
+ Arrays.stream(dataList).forEach(System.out::println);
+ }
- Data d1 = new Data("1","123",null);
- Data d2 = new Data("2","456",null);
- Data d3 = new Data("3","others",null);
- Data d4 = new Data("4","898",null);
+ @Test
+ public void test2_x() {
- List dataList = new ArrayList<>();
+ Data d1 = new Data("1", "123", null);
+ Data d2 = new Data("2", "456", null);
+ Data d3 = new Data("3", "others", null);
+ Data d4 = new Data("4", "898", null);
- dataList.add(d1);
- dataList.add(d3);
- dataList.add(d2);
- dataList.add(d4);
+ List dataList = new ArrayList<>();
- Data[] dataList2 = dataList.stream().toArray(Data[]::new);
+ dataList.add(d1);
+ dataList.add(d3);
+ dataList.add(d2);
+ dataList.add(d4);
- Arrays.stream(dataList2).forEach(System.out::println);
+ Data[] dataList2 = dataList.stream().toArray(Data[]::new);
- Arrays.sort(dataList2);
+ Arrays.stream(dataList2).forEach(System.out::println);
- System.out.println();
+ Arrays.sort(dataList2);
- Arrays.stream(dataList2).forEach(System.out::println);
- }
+ System.out.println();
- @Test
- public void test2_1(){
+ Arrays.stream(dataList2).forEach(System.out::println);
+ }
- Data d1 = new Data("1",null,null);
- Data d2 = new Data("2",null,null);
- Data d3 = new Data("3","others",null);
- Data d4 = new Data("4",null,null);
+ @Test
+ public void test2_1() {
- //Data[] dataList = new Data[]{d1,d4,d3,d2};
- List dataList = new ArrayList<>();
- //List dataList = Arrays.asList(d1, d2, d3);
- dataList.add(d1);
- dataList.add(d2);
- dataList.add(d3);
+ Data d1 = new Data("1", null, null);
+ Data d2 = new Data("2", null, null);
+ Data d3 = new Data("3", "others", null);
+ Data d4 = new Data("4", null, null);
- Integer idx = dataList.indexOf(d3);
+ // Data[] dataList = new Data[]{d1,d4,d3,d2};
+ List