From a52510f66bf5b6357adaddd189f70fe821cf0d51 Mon Sep 17 00:00:00 2001 From: yennanliu Date: Thu, 11 Jul 2024 16:17:51 +0800 Subject: [PATCH] add Test2, reformat all code --- src/main/java/Advances/CalendarApi/demo1.java | 93 ++- src/main/java/Advances/ClassLoader/demo1.java | 5 +- .../CollectionDemo/IteratorDemo1.java | 5 +- .../CollectionDemo/LinkedHashSetDemo1.java | 64 ++- .../Advances/CollectionDemo/ListDemo1.java | 3 +- .../Advances/CollectionDemo/SetDemo1.java | 127 ++--- .../Advances/CollectionDemo/TreeSetDemo1.java | 135 +++-- .../java/Advances/CollectionDemo/User.java | 2 +- .../java/Advances/CollectionDemo/demo1.java | 101 ++-- .../java/Advances/CollectionDemo/demo2.java | 15 +- .../java/Advances/CollectionDemo/demo3.java | 85 ++- .../Advances/CollectionDemo/foreachDemo1.java | 98 ++-- src/main/java/Advances/Collections/demo1.java | 3 +- .../Advances/ComparableComparator/demo1.java | 230 ++++---- src/main/java/Advances/DateTimeApi/demo1.java | 11 +- src/main/java/Advances/DateTimeApi/demo2.java | 2 +- src/main/java/Advances/DateTimeApi/demo3.java | 3 +- .../Advances/DateTimeFormatterApi/demo1.java | 4 +- .../DynamicProxy/StaticProxyDemo1.java | 2 +- .../DynamicProxy/StaticProxyDemo2.java | 3 +- src/main/java/Advances/Enumeration/demo1.java | 1 + src/main/java/Advances/Enumeration/demo2.java | 4 +- src/main/java/Advances/Enumeration/demo3.java | 2 +- src/main/java/Advances/Enumeration/demo4.java | 12 +- src/main/java/Advances/Enumeration/demo5.java | 6 +- src/main/java/Advances/FileIO/demo1.java | 60 +- src/main/java/Advances/FileIO/demo2.java | 8 +- src/main/java/Advances/FileIO/demo3.java | 92 +-- src/main/java/Advances/Generic/demo1.java | 139 +++-- src/main/java/Advances/Generic/demo2.java | 3 +- src/main/java/Advances/Generic/demo3.java | 98 ++-- src/main/java/Advances/Generic/demo4.java | 17 +- src/main/java/Advances/Generic/demo5.java | 3 +- src/main/java/Advances/Generic/demo6.java | 3 +- src/main/java/Advances/Generic/demo7.java | 40 +- src/main/java/Advances/Generic/demo8.java | 1 - src/main/java/Advances/Generic/demo9.java | 47 +- src/main/java/Advances/IOFlow/demo1.java | 4 +- src/main/java/Advances/IOFlow/demo2.java | 76 ++- src/main/java/Advances/IOFlow/demo3.java | 79 ++- src/main/java/Advances/IOFlow/demo4.java | 89 ++- src/main/java/Advances/IOFlow/demo5.java | 3 +- src/main/java/Advances/IOFlow/demo6.java | 216 ++++--- src/main/java/Advances/IOFlow/demo7.java | 97 ++-- src/main/java/Advances/IOFlow/demo8.java | 3 +- src/main/java/Advances/IOFlow2/demo1.java | 111 ++-- src/main/java/Advances/IOFlow3/demo1.java | 160 +++--- src/main/java/Advances/IOFlow3/demo2.java | 90 ++- src/main/java/Advances/InstantApi/demo1.java | 3 +- src/main/java/Advances/Lambda/demo1.java | 80 ++- src/main/java/Advances/Lambda/demo2.java | 272 +++++---- src/main/java/Advances/Lambda/demo3.java | 144 ++--- .../Lambda/demo4/ConstructorRefTest.java | 164 +++--- .../Advances/Lambda/demo4/MethodRefTest.java | 5 +- .../java/Advances/LocalDateTime/demo1.java | 83 ++- src/main/java/Advances/MapDemo/demo1.java | 3 +- src/main/java/Advances/MapDemo/demo2.java | 3 +- .../Advances/ObjectInputOutputFlow/demo1.java | 121 ++-- .../Advances/ObjectInputOutputFlow/demo2.java | 146 ++--- src/main/java/Advances/Optional/demo1.java | 3 +- .../java/Advances/RandomAccessFile/demo1.java | 177 +++--- .../Advances/Reflection/MyAnnotation.java | 4 +- src/main/java/Advances/Reflection/demo1.java | 293 +++++----- src/main/java/Advances/Reflection/demo3.java | 73 ++- src/main/java/Advances/Reflection/demo4.java | 96 ++-- src/main/java/Advances/Reflection/demo5.java | 146 +++-- src/main/java/Advances/Reflection/demo6.java | 2 +- src/main/java/Advances/Reflection/demo7.java | 2 +- src/main/java/Advances/Reflection/demo8.java | 83 ++- src/main/java/Advances/Reflection/demo9.java | 76 ++- src/main/java/Advances/StreamAPI/demo1.java | 4 +- src/main/java/Advances/StreamAPI/demo2.java | 350 ++++++------ src/main/java/Advances/StreamAPI/demo3.java | 4 +- src/main/java/Advances/StreamAPI/demo4.java | 76 +-- .../StringBufferStringBuilder1/demo1.java | 2 +- src/main/java/Advances/StringClass/demo2.java | 13 +- .../java/Advances/StringMethod/demo2.java | 4 +- .../java/Advances/StringTransform/demo1.java | 133 +++-- .../Advances/SystemGetPropertiesDemo1.java | 6 +- .../ThreadCommunication2/ProductTest.java | 218 ++++--- .../ThreadDemo4/ThreadMethodDemo3.java | 2 +- .../Advances/ThreadDemo6/CallableDemo1.java | 2 +- src/main/java/Advances/ThreadPool1/demo1.java | 83 ++- .../java/Advances/ThreadSafety2/demo1.java | 2 +- .../Advances/ThreadSafety3/AccountDemo1.java | 2 +- src/main/java/Advances/TreeMap/User.java | 2 +- src/main/java/Advances/TreeMap/demo1.java | 97 ++-- src/main/java/Advances/internet/demo2.java | 5 +- src/main/java/Advances/internet/demo3.java | 93 ++- src/main/java/Advances/internet/demo4.java | 151 +++-- src/main/java/Advances/internet/demo5.java | 54 +- .../java/Basics/AbstractDemo3/PersonTest.java | 8 +- src/main/java/Basics/Constructor1.java | 1 + .../CustomerCRM/service/CustomerList.java | 2 +- .../CustomerCRM/service/TeamService.java | 2 +- .../Basics/CustomerCRM/utils/CMUtility.java | 2 +- .../Basics/CustomerCRM/view/CustomerView.java | 23 +- .../Basics/CustomerCRM/view/TeamView.java | 4 +- src/main/java/Basics/DynamicNumVar1.java | 2 +- .../EmployeeCRM/team/domain/Architect.java | 2 +- .../EmployeeCRM/team/domain/Programmer.java | 111 ++-- .../team/service/NameListService.java | 2 +- .../EmployeeCRM/team/service/Status.java | 3 +- .../EmployeeCRM/team/service/TeamService.java | 2 +- .../EmployeeCRM/team/utils/TSUtility.java | 2 +- .../EmployeeCRM/team/view/TeamView.java | 196 +++---- src/main/java/Basics/EqualsDemo1/demo1.java | 4 +- src/main/java/Basics/EqualsDemo1/demo2.java | 4 +- src/main/java/Basics/EqualsDemo4/test1.java | 4 +- src/main/java/Basics/ExceptionDemo1.java | 3 +- src/main/java/Basics/ExceptionDemo2.java | 3 +- src/main/java/Basics/ExceptionDemo3.java | 6 +- src/main/java/Basics/ExceptionDemo4.java | 6 +- src/main/java/Basics/ExceptionDemo8.java | 4 +- src/main/java/Basics/GetterSetterDemo2.java | 2 +- src/main/java/Basics/HashMapDemo1.java | 28 +- src/main/java/Basics/ImportDemo1.java | 17 +- src/main/java/Basics/JUnit_1/JUnitTest.java | 65 +-- src/main/java/Basics/Overloading1.java | 4 +- src/main/java/Basics/ProxyDemo1.java | 4 +- src/main/java/Basics/ProxyDemo2.java | 2 +- src/main/java/Basics/SingletonDemo1.java | 7 +- src/main/java/Basics/SingletonDemo2.java | 7 +- src/main/java/Basics/SingletonDemo3.java | 3 +- src/main/java/Basics/TimeZone/demo1.java | 4 +- src/main/java/Basics/ToString_1.java | 10 +- .../java/Basics/WrapperDemo1/WrapperTest.java | 8 +- .../Basics/WrapperDemo1/WrapperTest3.java | 3 + src/main/java/Basics/forLoop2.java | 41 +- src/main/java/Basics/interfaceDemo1.java | 4 +- src/main/java/Basics/interfaceDemo2.java | 185 +++--- .../Basics/interfaceDemo4/CompareObject.java | 2 +- .../Basics/interfaceDemo5/CompareObject.java | 2 +- src/main/java/Basics/interfaceDemo5/test.java | 2 +- .../java/Basics/interfaceDemo6/CompareA.java | 4 +- src/main/java/Basics/objectDemo1/GCdemo1.java | 2 +- .../java/Basics/objectDemo2/testCircle.java | 5 +- .../java/Basics/polymorphism_2/OrderTest.java | 7 +- src/main/java/Basics/staticDemo3.java | 8 +- src/main/java/Basics/staticDemo5.java | 146 +++-- src/main/java/Basics/staticDemo6/Account.java | 2 +- src/main/java/Basics/staticDemo6/test.java | 8 +- src/main/java/Basics/thisDemo2.java | 2 +- src/main/java/Basics/thisDemo3/Account.java | 106 ++-- src/main/java/Basics/thisDemo3/Customer.java | 4 +- src/main/java/Basics/thisDemo5/Bank.java | 2 +- src/main/java/Basics/thisDemo5/Customer.java | 4 +- src/main/java/Basics/valueTransfer1.java | 3 +- .../java/DesignPattern/Builder/demo1.java | 10 +- .../java/DesignPattern/Factory/demo1.java | 2 +- .../java/DesignPattern/Singleton/Hungry.java | 2 +- src/main/java/Others/FreeMarker/demo1.java | 10 +- src/main/java/Workspace/workspace3.java | 3 - src/main/java/dev/ArrayTest.java | 1 - src/main/java/dev/CSV2Json.java | 7 +- src/main/java/dev/CustomSortingTest.java | 295 +++++----- src/main/java/dev/FastJsonTest1.java | 93 +-- src/main/java/dev/FileIOTest.java | 33 +- src/main/java/dev/FileTest.java | 55 +- src/main/java/dev/ForLoopFunc.java | 1 - src/main/java/dev/IFileUtilsTest.java | 19 +- src/main/java/dev/ParseCSVTest.java | 84 +-- src/main/java/dev/StreamTest1.java | 199 ++++--- src/main/java/dev/StringTest.java | 534 +++++++++--------- src/main/java/dev/TimeStampTest.java | 3 +- src/main/java/dev/bean/BigDecimalTest.java | 21 +- src/main/java/dev/bean/Data.java | 133 +++-- src/main/java/threadDev/Fibonacci.java | 30 +- src/main/java/threadDev/Test1.java | 117 ++-- src/main/java/threadDev/Test2.java | 37 ++ src/main/java/utils/ParseValue.java | 19 +- 171 files changed, 4164 insertions(+), 4380 deletions(-) create mode 100644 src/main/java/threadDev/Test2.java diff --git a/src/main/java/Advances/CalendarApi/demo1.java b/src/main/java/Advances/CalendarApi/demo1.java index 273e7745..6a4c79ff 100644 --- a/src/main/java/Advances/CalendarApi/demo1.java +++ b/src/main/java/Advances/CalendarApi/demo1.java @@ -2,78 +2,73 @@ // https://www.youtube.com/watch?v=aPgJYCIc-fM&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=482 - -/** CalendarApi demo1 : +/** + * CalendarApi demo1 : * - * Calendar class use class intro + *

Calendar class use class intro */ - import java.util.Calendar; import java.util.Date; import org.junit.jupiter.api.Test; /** - * 1) Calendar is an abstract class + * 1) Calendar is an abstract class * - * 2) there are 2 ways to instantiate it + *

2) there are 2 ways to instantiate it * - * - 2-1) create its sub-class' class (GregorianCalendar) - * - 2-2) call its static method : getInstance() + *

- 2-1) create its sub-class' class (GregorianCalendar) - 2-2) call its static method : + * getInstance() * - * // these 2 methods are the same actually + *

// these 2 methods are the same actually * - * 3) frequent used methods + *

3) frequent used methods * - * - 3-1) get() - * - 3-2) set() - * - 3-3) add() - * - 3-4) getTime() - * - 3-5) setTime() + *

- 3-1) get() - 3-2) set() - 3-3) add() - 3-4) getTime() - 3-5) setTime() */ public class demo1 { - @Test - public void test1(){ - // 2-2) call its static method : getInstance() - Calendar calendar = Calendar.getInstance(); - System.out.println(calendar.getClass()); // still class java.util.GregorianCalendar - } + @Test + public void test1() { + // 2-2) call its static method : getInstance() + Calendar calendar = Calendar.getInstance(); + System.out.println(calendar.getClass()); // still class java.util.GregorianCalendar + } - @Test - public void test2(){ - Calendar calendar = Calendar.getInstance(); + @Test + public void test2() { + Calendar calendar = Calendar.getInstance(); - // get() - System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); - System.out.println(calendar.get(Calendar.DAY_OF_WEEK)); - System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); - System.out.println(calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH)); + // get() + System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); + System.out.println(calendar.get(Calendar.DAY_OF_WEEK)); + System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); + System.out.println(calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH)); - System.out.println("--------------------------"); + System.out.println("--------------------------"); - // set() : change DAY_OF_MONTH or ... in Calendar - System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); - calendar.set(Calendar.DAY_OF_MONTH, 1); - System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); + // set() : change DAY_OF_MONTH or ... in Calendar + System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); + calendar.set(Calendar.DAY_OF_MONTH, 1); + System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); - System.out.println("--------------------------"); + System.out.println("--------------------------"); - // add() - System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); - calendar.add(Calendar.DAY_OF_MONTH, 3); - System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); + // add() + System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); + calendar.add(Calendar.DAY_OF_MONTH, 3); + System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); - System.out.println("--------------------------"); + System.out.println("--------------------------"); - // getTime() : Calendar dtype -> Date dtype - Date date = calendar.getTime(); - System.out.println(date); + // getTime() : Calendar dtype -> Date dtype + Date date = calendar.getTime(); + System.out.println(date); - System.out.println("--------------------------"); + System.out.println("--------------------------"); - // setTime() : Date dtype -> Calendar dtype - Date date1 = new Date(); - calendar.setTime(date1); // set calendar from date1 - System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); - } + // setTime() : Date dtype -> Calendar dtype + Date date1 = new Date(); + calendar.setTime(date1); // set calendar from date1 + System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); + } } diff --git a/src/main/java/Advances/ClassLoader/demo1.java b/src/main/java/Advances/ClassLoader/demo1.java index 49dadf73..304ffeb2 100644 --- a/src/main/java/Advances/ClassLoader/demo1.java +++ b/src/main/java/Advances/ClassLoader/demo1.java @@ -3,13 +3,10 @@ // https://www.youtube.com/watch?v=rePjvHVWnQ0&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=643 // https://www.youtube.com/watch?v=bpP8CE98MhE&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=644 -import org.junit.jupiter.api.Test; - -import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.InputStream; import java.util.Properties; +import org.junit.jupiter.api.Test; public class demo1 { diff --git a/src/main/java/Advances/CollectionDemo/IteratorDemo1.java b/src/main/java/Advances/CollectionDemo/IteratorDemo1.java index 189ba560..7589175a 100644 --- a/src/main/java/Advances/CollectionDemo/IteratorDemo1.java +++ b/src/main/java/Advances/CollectionDemo/IteratorDemo1.java @@ -3,11 +3,10 @@ // https://www.youtube.com/watch?v=HA7LSr6-xls&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=525 /** Iterator demo 1 */ -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; +import org.junit.jupiter.api.Test; /** * Iterator Demo1 -> collection iteration op, via Iterator interface @@ -27,7 +26,7 @@ public void test1() { col1.add(456); col1.add(789); col1.add("yooooo"); - col1.add(new String("kate")); + col1.add("kate"); col1.add(new Person("kyo", 19)); Iterator iterator = col1.iterator(); diff --git a/src/main/java/Advances/CollectionDemo/LinkedHashSetDemo1.java b/src/main/java/Advances/CollectionDemo/LinkedHashSetDemo1.java index 8d96b1ab..d2d2f4c5 100644 --- a/src/main/java/Advances/CollectionDemo/LinkedHashSetDemo1.java +++ b/src/main/java/Advances/CollectionDemo/LinkedHashSetDemo1.java @@ -3,7 +3,6 @@ // https://www.youtube.com/watch?v=z8nlH3W1sBU&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=538 /** LinkedHashSet demo 1 */ - import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; @@ -11,34 +10,41 @@ public class LinkedHashSetDemo1 { - @Test - public void test1(){ - /** - * LinkedHashSet demo 1 - * - * 1) LinkedHashSet is HashSet's sub class - * - * 2) maintain 2 references when adding new element : pre element and next element - * - * 3) pros : good performance in looping, adding, deletion - * - * 4) cons : - */ - - Set set = new LinkedHashSet(); - set.add(456); - set.add(123); - set.add(123); // only storage one "123", since HashSet is non-duplicated - set.add("aa"); - set.add("bb"); - set.add(new Person("tim",11)); - set.add(new Person("tim",11)); // NOTE : will storage 2 "Person("tim",11)" since we haven't overwrote "equals", "hashCode" methods in Person class - set.add(new User("ann",20)); - set.add(new User("ann",20)); // NOTE : only storage 1 "User("ann",20)" if we overwrite "equals", "hashCode" methods in User class + @Test + public void test1() { + /** + * LinkedHashSet demo 1 + * + *

1) LinkedHashSet is HashSet's sub class + * + *

2) maintain 2 references when adding new element : pre element and next element + * + *

3) pros : good performance in looping, adding, deletion + * + *

4) cons : + */ + Set set = new LinkedHashSet(); + set.add(456); + set.add(123); + set.add(123); // only storage one "123", since HashSet is non-duplicated + set.add("aa"); + set.add("bb"); + set.add(new Person("tim", 11)); + set.add( + new Person( + "tim", + 11)); // NOTE : will storage 2 "Person("tim",11)" since we haven't overwrote "equals", + // "hashCode" methods in Person class + set.add(new User("ann", 20)); + set.add( + new User( + "ann", + 20)); // NOTE : only storage 1 "User("ann",20)" if we overwrite "equals", "hashCode" + // methods in User class - Iterator iterator = set.iterator(); - while (iterator.hasNext()){ - System.out.println(iterator.next()); - } + Iterator iterator = set.iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); } + } } diff --git a/src/main/java/Advances/CollectionDemo/ListDemo1.java b/src/main/java/Advances/CollectionDemo/ListDemo1.java index 28ef1af6..dee41a03 100644 --- a/src/main/java/Advances/CollectionDemo/ListDemo1.java +++ b/src/main/java/Advances/CollectionDemo/ListDemo1.java @@ -6,11 +6,10 @@ // https://www.youtube.com/watch?v=KptmLcdTECg&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=531 /** List demo 1 */ -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import org.junit.jupiter.api.Test; /** * List Demo1 |-- List interface : storage ordering, duplicated record -> "dynamic" array |--- diff --git a/src/main/java/Advances/CollectionDemo/SetDemo1.java b/src/main/java/Advances/CollectionDemo/SetDemo1.java index 7bf3d0ce..0a375433 100644 --- a/src/main/java/Advances/CollectionDemo/SetDemo1.java +++ b/src/main/java/Advances/CollectionDemo/SetDemo1.java @@ -6,85 +6,82 @@ // https://www.youtube.com/watch?v=fWaabv-UgCs&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=537 /** Set demo 1 */ - import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.junit.jupiter.api.Test; /** - * Set Demo 1 + * Set Demo 1 * - * 0) "Set" is an interface, we need to implement it before using. - * plz check below implemented classes + *

0) "Set" is an interface, we need to implement it before using. plz check below implemented + * classes * - * 1) Collection framework: - * .... - * |--- Set interface : storage non-ordering, non-repeatable elements - * |--- HashSet, LinkedHastSet, TreeSet + *

1) Collection framework: .... |--- Set interface : storage non-ordering, non-repeatable + * elements |--- HashSet, LinkedHastSet, TreeSet * - * 2) 3 implemented classes (Set) - * - HashSet : main implemented class (Set interface), thread Un-safety, can save `null` value - * - LinkedHastSet : "HashSet"'s sub class. hashset with linkedlist structure. make looping/add/delete elements more efficient - * - TreeSet : use "Red–black tree" in low level. can ordering input elements based on their properties + *

2) 3 implemented classes (Set) - HashSet : main implemented class (Set interface), thread + * Un-safety, can save `null` value - LinkedHastSet : "HashSet"'s sub class. hashset with linkedlist + * structure. make looping/add/delete elements more efficient - TreeSet : use "Red–black tree" in + * low level. can ordering input elements based on their properties * - * 3) There are NO extra defined methods in Set -> all methods it (Set) has are as SAME as Collections's (methods) + *

3) There are NO extra defined methods in Set -> all methods it (Set) has are as SAME as + * Collections's (methods) * - * 4) requirement : - * - when add element to HashSet -> we need to Overwrite hashCode() and equals() methods - * - Overwritten hashCode() and equals() methods should be "consistency" -> e.g. same elements SHOULD have SAME hash value + *

4) requirement : - when add element to HashSet -> we need to Overwrite hashCode() and equals() + * methods - Overwritten hashCode() and equals() methods should be "consistency" -> e.g. same + * elements SHOULD have SAME hash value */ - public class SetDemo1 { - @Test - public void test1(){ - /** - * Set : storage non-ordering, non-duplicated (HashSet) - * - * 0) HashSet : array + linked list (low level structure) - * - * 1) non-ordering : - * - non-ordering != randomness - * - ordering in storage space is NOT based on input ordering, BUT on record's hash value - * - * 2) non-duplicated - * - check duplicated or not (added elements) based on "equals()" method - * - Need to overwrite "equals", "hashCode" methods if user-defined class - * - can only add "one" same element into HashSet - * - plz check below "set.add(new User("ann",20))" example - * - * 3) adding element steps (HashSet) - * - step 1) when we add element a to HashSet - * - step 2) get its hash value via its class' hashCode() method - * - step 3) then get storage address (in storage space) via hash value above - * - step 4) check if there is already element on the address - * - if False : add element a OK - * - if True : compare element a and b's hash value (if there is already an element b on the address) //(case 1) - * - if False: add element a OK - * - if True: call class' equals() method, compare every part in element a and element b //(case 2) - * - if True (equals()): add element a Failed //(case 3) - * - if False (equals()): add element a OK - * - * - (for success case 2, case 3, element a will be saved as Linked list form) - * - (JDK 7 : put element a into array, point a -> original element) - * - (JDK 8 : point original element -> element a) - */ - - Set set = new HashSet(); - set.add(456); - set.add(123); - set.add(123); // only storage one "123", since HashSet is non-duplicated - set.add("aa"); - set.add("bb"); - set.add(new Person("tim",11)); - set.add(new Person("tim",11)); // NOTE : will storage 2 "Person("tim",11)" since we haven't overwritten "equals", "hashCode" methods in Person class - set.add(new User("ann",20)); - set.add(new User("ann",20)); // NOTE : only storage 1 "User("ann",20)" if we overwrite "equals", "hashCode" methods in User class + @Test + public void test1() { + /** + * Set : storage non-ordering, non-duplicated (HashSet) + * + *

0) HashSet : array + linked list (low level structure) + * + *

1) non-ordering : - non-ordering != randomness - ordering in storage space is NOT based on + * input ordering, BUT on record's hash value + * + *

2) non-duplicated - check duplicated or not (added elements) based on "equals()" method - + * Need to overwrite "equals", "hashCode" methods if user-defined class - can only add "one" + * same element into HashSet - plz check below "set.add(new User("ann",20))" example + * + *

3) adding element steps (HashSet) - step 1) when we add element a to HashSet - step 2) get + * its hash value via its class' hashCode() method - step 3) then get storage address (in + * storage space) via hash value above - step 4) check if there is already element on the + * address - if False : add element a OK - if True : compare element a and b's hash value (if + * there is already an element b on the address) //(case 1) - if False: add element a OK - if + * True: call class' equals() method, compare every part in element a and element b //(case 2) - + * if True (equals()): add element a Failed //(case 3) - if False (equals()): add element a OK + * + *

- (for success case 2, case 3, element a will be saved as Linked list form) - (JDK 7 : put + * element a into array, point a -> original element) - (JDK 8 : point original element -> + * element a) + */ + Set set = new HashSet(); + set.add(456); + set.add(123); + set.add(123); // only storage one "123", since HashSet is non-duplicated + set.add("aa"); + set.add("bb"); + set.add(new Person("tim", 11)); + set.add( + new Person( + "tim", + 11)); // NOTE : will storage 2 "Person("tim",11)" since we haven't overwritten "equals", + // "hashCode" methods in Person class + set.add(new User("ann", 20)); + set.add( + new User( + "ann", + 20)); // NOTE : only storage 1 "User("ann",20)" if we overwrite "equals", "hashCode" + // methods in User class - Iterator iterator = set.iterator(); - while (iterator.hasNext()){ - System.out.println(iterator.next()); - } + Iterator iterator = set.iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); } + } } diff --git a/src/main/java/Advances/CollectionDemo/TreeSetDemo1.java b/src/main/java/Advances/CollectionDemo/TreeSetDemo1.java index fbc09a0e..c0988ea3 100644 --- a/src/main/java/Advances/CollectionDemo/TreeSetDemo1.java +++ b/src/main/java/Advances/CollectionDemo/TreeSetDemo1.java @@ -6,105 +6,100 @@ /** TreeSet demo 1 */ /** - * 0) red-black tree as low level structure + * 0) red-black tree as low level structure * - * 1) CAN ONLY add SAME CLASS elements into TreeSet + *

1) CAN ONLY add SAME CLASS elements into TreeSet * - * 2) 2 ordering types: - * - natural ordering - * - custom ordering + *

2) 2 ordering types: - natural ordering - custom ordering * - * 3) natural ordering : - * - compare if 2 elements are the same : "compareTo() method returns 0", not using "equals()" anymore + *

3) natural ordering : - compare if 2 elements are the same : "compareTo() method returns 0", + * not using "equals()" anymore * - * 4) custom ordering : - * - compare if 2 elements are the same : "compare() method returns 0", not using "equals()" anymore - * - * - * 5) Compare "comparision" in different classes: - * Set, HashSet : hashCode(), equals() - * TreeSet : compareTo(), compare() + *

4) custom ordering : - compare if 2 elements are the same : "compare() method returns 0", not + * using "equals()" anymore * + *

5) Compare "comparision" in different classes: Set, HashSet : hashCode(), equals() TreeSet : + * compareTo(), compare() */ - import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet; import org.junit.jupiter.api.Test; public class TreeSetDemo1 { - @Test - public void test1(){ - TreeSet set1 = new TreeSet(); + @Test + public void test1() { + TreeSet set1 = new TreeSet(); // below is wrong : can only add elements belong to same class // set1.add(123); // set1.add(456); // set1.add("abc"); - // below is OK - set1.add(123); - set1.add(345); - set1.add(7); - set1.add(-107); + // below is OK + set1.add(123); + set1.add(345); + set1.add(7); + set1.add(-107); - Iterator iterator = set1.iterator(); - while (iterator.hasNext()){ - System.out.println(iterator.next()); - } + Iterator iterator = set1.iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); } + } - @Test - public void test2(){ - /** demo : natural ordering */ - TreeSet set1 = new TreeSet(); + @Test + public void test2() { + /** demo : natural ordering */ + TreeSet set1 = new TreeSet(); - set1.add(new User("zack", 99)); - set1.add(new User("kk", 10)); - set1.add(new User("jessy", 30)); - set1.add(new User("amy", 20)); - set1.add(new User("amy", 23)); + set1.add(new User("zack", 99)); + set1.add(new User("kk", 10)); + set1.add(new User("jessy", 30)); + set1.add(new User("amy", 20)); + set1.add(new User("amy", 23)); - Iterator iterator = set1.iterator(); - while (iterator.hasNext()){ - System.out.println(iterator.next()); - } + Iterator iterator = set1.iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); } + } - @Test - public void test3(){ - /** demo : custom ordering */ - /** create custom Comparator (for custom ordering) */ - Comparator com = new Comparator() { - // order by age (small -> big) (if same age, neglect) - @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()); - }else{ - throw new RuntimeException("input type not match !"); - } + @Test + public void test3() { + /** demo : custom ordering */ + /** create custom Comparator (for custom ordering) */ + Comparator com = + new Comparator() { + // order by age (small -> big) (if same age, neglect) + @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()); + } else { + throw new RuntimeException("input type not match !"); } + } }; - /** - * without param -> natural ordering (e.g. TreeSet set1 = new TreeSet();) - * with param -> custom ordering (e.g. TreeSet set1 = new TreeSet(com);) - */ - TreeSet set1 = new TreeSet(com); + /** + * without param -> natural ordering (e.g. TreeSet set1 = new TreeSet();) with param -> custom + * ordering (e.g. TreeSet set1 = new TreeSet(com);) + */ + TreeSet set1 = new TreeSet(com); - set1.add(new User("zack", 99)); - set1.add(new User("kk", 10)); - set1.add(new User("jessy", 30)); - set1.add(new User("amy", 20)); - set1.add(new User("amy", 23)); - set1.add(new User("betty", 23)); + set1.add(new User("zack", 99)); + set1.add(new User("kk", 10)); + set1.add(new User("jessy", 30)); + set1.add(new User("amy", 20)); + set1.add(new User("amy", 23)); + set1.add(new User("betty", 23)); - Iterator iterator = set1.iterator(); - while (iterator.hasNext()){ - System.out.println(iterator.next()); - } + Iterator iterator = set1.iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); } + } } diff --git a/src/main/java/Advances/CollectionDemo/User.java b/src/main/java/Advances/CollectionDemo/User.java index a92f5311..3b33ea63 100644 --- a/src/main/java/Advances/CollectionDemo/User.java +++ b/src/main/java/Advances/CollectionDemo/User.java @@ -7,7 +7,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/CollectionDemo/demo1.java b/src/main/java/Advances/CollectionDemo/demo1.java index dbafd445..d1b6f7c7 100644 --- a/src/main/java/Advances/CollectionDemo/demo1.java +++ b/src/main/java/Advances/CollectionDemo/demo1.java @@ -5,81 +5,68 @@ // https://www.youtube.com/watch?v=WO-54GprY0M&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=519 /** Collection demo 1 */ - import java.util.ArrayList; import java.util.Collection; import org.junit.jupiter.api.Test; /** - * Collection demo 1 - * - * 1) collection, array are structure/container for data storage/manipulation - * (internal storage, (not persistent storage, e.g. .txt, .csv, DB..) ) + * Collection demo 1 * - * 2) array - * - 2-1) length is fixed (not dynamic) once initialized - * - length is NOT changeable once initialized - * - 2-2) need to define element type, element is fixed (not dynamic); polymorphism is possible - * - e.g. : String[] arr; - * - e.g. : int[] arr; - * - ONLY has one element type (but polymorphism is possible) - * - 2-3) array only offers limited methods, hard to do op such as : add, delete, modify, find - * - 2-4) low efficiency for some op - * - e.g. add : need to update, move idx for many elements - * - 2-5) ordering, repeatable + *

1) collection, array are structure/container for data storage/manipulation (internal storage, + * (not persistent storage, e.g. .txt, .csv, DB..) ) * - * 3) Collection framework: - * - Collection interface : single array collection, for storage every single element - * |--- List interface : storage ordering, repeatable element --> "dynamic" array - * |--- ArrayList : LinkedList, Vector - * |--- Set interface : storage non-ordering, non-repeatable element - * |--- HashSet, LinkedHastSet, TreeSet - * |--- Map interface : double array collection, storage key-value pair - * |--- HashMap, LinkedHashMap, TreeMap, HashTable, Properties + *

2) array - 2-1) length is fixed (not dynamic) once initialized - length is NOT changeable once + * initialized - 2-2) need to define element type, element is fixed (not dynamic); polymorphism is + * possible - e.g. : String[] arr; - e.g. : int[] arr; - ONLY has one element type (but polymorphism + * is possible) - 2-3) array only offers limited methods, hard to do op such as : add, delete, + * modify, find - 2-4) low efficiency for some op - e.g. add : need to update, move idx for many + * elements - 2-5) ordering, repeatable * - * 4) Collection methods - * - + *

3) Collection framework: - Collection interface : single array collection, for storage every + * single element |--- List interface : storage ordering, repeatable element --> "dynamic" array + * |--- ArrayList : LinkedList, Vector |--- Set interface : storage non-ordering, non-repeatable + * element |--- HashSet, LinkedHastSet, TreeSet |--- Map interface : double array collection, + * storage key-value pair |--- HashMap, LinkedHashMap, TreeMap, HashTable, Properties * + *

4) Collection methods - */ - - public class demo1 { - @Test - public void test1(){ - Collection col1 = new ArrayList(); + @Test + public void test1() { + Collection col1 = new ArrayList(); - // add(Object e) - col1.add("aa"); - col1.add("bb"); - col1.add(123); - col1.add("dd"); + // add(Object e) + col1.add("aa"); + col1.add("bb"); + col1.add(123); + col1.add("dd"); - System.out.println(col1); - System.out.println("----------"); + System.out.println(col1); + System.out.println("----------"); - // size() - System.out.println(col1.size()); - System.out.println("----------"); + // size() + System.out.println(col1.size()); + System.out.println("----------"); - // addAll() - Collection col2 = new ArrayList(); - col2.add(789); - col2.add("xyz"); + // addAll() + Collection col2 = new ArrayList(); + col2.add(789); + col2.add("xyz"); - System.out.println(col2); - System.out.println("----------"); + System.out.println(col2); + System.out.println("----------"); - col1.addAll(col2); + col1.addAll(col2); - System.out.println(col1); - System.out.println("----------"); + System.out.println(col1); + System.out.println("----------"); - // isEmpty : check if there is an element in ArrayList - System.out.println(col1.isEmpty()); - System.out.println("----------"); + // isEmpty : check if there is an element in ArrayList + System.out.println(col1.isEmpty()); + System.out.println("----------"); - // clear() : clear all elements in ArrayList - col2.clear(); - System.out.println(col2); - } + // clear() : clear all elements in ArrayList + col2.clear(); + System.out.println(col2); + } } diff --git a/src/main/java/Advances/CollectionDemo/demo2.java b/src/main/java/Advances/CollectionDemo/demo2.java index b3c82f4d..61f26155 100644 --- a/src/main/java/Advances/CollectionDemo/demo2.java +++ b/src/main/java/Advances/CollectionDemo/demo2.java @@ -6,11 +6,10 @@ // https://www.youtube.com/watch?v=hyj5uygJyLU&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=520 // https://www.youtube.com/watch?v=hyj5uygJyLU&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=520 -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import org.junit.jupiter.api.Test; /** * Collection interface method demo @@ -28,7 +27,7 @@ public void test1() { col1.add(123); col1.add(456); col1.add("yooooo"); - col1.add(new String("kate")); + col1.add("kate"); Person p = new Person("tom", 20); col1.add(p); col1.add(new Person("kyo", 19)); @@ -39,7 +38,7 @@ public void test1() { // Contains(Object obj) : check if current collections has obj // *** Will use obj class' `equals()` when check above // --> if needed, we can override obj class' `equals()` - System.out.println(col1.contains(new String("kate"))); // true + System.out.println(col1.contains("kate")); // true System.out.println( col1.contains( @@ -69,7 +68,7 @@ public void test3() { col1.add(123); col1.add(456); col1.add("yooooo"); - col1.add(new String("kate")); + col1.add("kate"); col1.add(new Person("kyo", 19)); System.out.println(col1.remove(123)); @@ -127,7 +126,7 @@ public void test7() { col1.add(456); col1.add(789); col1.add("yooooo"); - col1.add(new String("kate")); + col1.add("kate"); col1.add(new Person("kyo", 19)); col1.remove(123); @@ -155,7 +154,7 @@ public void test8() { col1.add(456); col1.add(789); col1.add("yooooo"); - col1.add(new String("kate")); + col1.add("kate"); col1.add(new Person("kyo", 19)); Collection col2 = Arrays.asList(456, 789); @@ -174,7 +173,7 @@ public void test9() { col1.add(456); col1.add(789); col1.add("yooooo"); - col1.add(new String("kate")); + col1.add("kate"); col1.add(new Person("kyo", 19)); Collection col2 = Arrays.asList(456, 789); diff --git a/src/main/java/Advances/CollectionDemo/demo3.java b/src/main/java/Advances/CollectionDemo/demo3.java index 4a52169a..a469a22d 100644 --- a/src/main/java/Advances/CollectionDemo/demo3.java +++ b/src/main/java/Advances/CollectionDemo/demo3.java @@ -3,7 +3,6 @@ // https://www.youtube.com/watch?v=ScNzqfIzkS8&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=520 /** Collection demo 3 */ - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -12,59 +11,59 @@ public class demo3 { - @Test - public void test1(){ - - /** hashCode() : return current object hash code */ + @Test + public void test1() { - Collection col1 = new ArrayList(); - col1.add(123); - - System.out.println(col1.hashCode()); - } + /** hashCode() : return current object hash code */ + Collection col1 = new ArrayList(); + col1.add(123); - @Test - public void test2(){ + System.out.println(col1.hashCode()); + } - /** collection --> array (toArray()) */ + @Test + public void test2() { - Collection col1 = new ArrayList(); - col1.add(123); - col1.add(456); - col1.add(789); - col1.add("yooooo"); - col1.add(new String("kate")); - col1.add(new Person("kyo", 19)); + /** collection --> array (toArray()) */ + Collection col1 = new ArrayList(); + col1.add(123); + col1.add(456); + col1.add(789); + col1.add("yooooo"); + col1.add("kate"); + col1.add(new Person("kyo", 19)); - Object[] arr = col1.toArray(); - for (int i = 0; i < arr.length; i++){ - System.out.println(arr[i]); - } + Object[] arr = col1.toArray(); + for (int i = 0; i < arr.length; i++) { + System.out.println(arr[i]); + } - System.out.println("-----------------"); + System.out.println("-----------------"); - /** array --> collection ( via static method : Arrays.asList() ) */ - //Collection col1_ = Arrays.asList(arr); + /** array --> collection ( via static method : Arrays.asList() ) */ + // Collection col1_ = Arrays.asList(arr); - List list_1 = Arrays.asList(new String[]{"aa","bb","cc"}); - System.out.println(list_1); + List list_1 = Arrays.asList("aa", "bb", "cc"); + System.out.println(list_1); - List list_2 = Arrays.asList(new int[]{123, 456}); - System.out.println(list_2); // [[I@589b3632] + List list_2 = Arrays.asList(new int[] {123, 456}); + System.out.println(list_2); // [[I@589b3632] - List list_3 = Arrays.asList(123, 456); - System.out.println(list_3); // [123, 456] + List list_3 = Arrays.asList(123, 456); + System.out.println(list_3); // [123, 456] - List list_4 = Arrays.asList(new Integer[]{123, 456}); - System.out.println(list_4); // [123, 456], we need to use "Packaging class" (Integer) instead of basic data type (int) - } + List list_4 = Arrays.asList(123, 456); + System.out.println( + list_4); // [123, 456], we need to use "Packaging class" (Integer) instead of basic data + // type (int) + } - @Test - public void test3(){ + @Test + public void test3() { - /** iterator() : - * return Iterator interface instance, for visiting all elements in collection, - * -> plz check details in src/main/java/Advances/CollectionDemo/IteratorDemo1.java - */ - } + /** + * iterator() : return Iterator interface instance, for visiting all elements in collection, -> + * plz check details in src/main/java/Advances/CollectionDemo/IteratorDemo1.java + */ + } } diff --git a/src/main/java/Advances/CollectionDemo/foreachDemo1.java b/src/main/java/Advances/CollectionDemo/foreachDemo1.java index 0e7de8a6..f06f86a2 100644 --- a/src/main/java/Advances/CollectionDemo/foreachDemo1.java +++ b/src/main/java/Advances/CollectionDemo/foreachDemo1.java @@ -3,75 +3,75 @@ // https://www.youtube.com/watch?v=Qqxj6k1xI5I&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=526 /** foreach demo 1 */ - import java.util.ArrayList; import java.util.Collection; import org.junit.jupiter.api.Test; /** - * foreach : for looping over collection, array + * foreach : for looping over collection, array * - * 1) since JDK 5.0 + *

1) since JDK 5.0 * - * 2) general form : - * -> for(element-type local-variable : collection-object) + *

2) general form : -> for(element-type local-variable : collection-object) */ - public class foreachDemo1 { - @Test - public void test1(){ - - Collection col1 = new ArrayList(); - col1.add(123); - col1.add(456); - col1.add(789); - col1.add("yooooo"); - col1.add(new String("kate")); - col1.add(new Person("kyo", 19)); - col1.add(false); - - // for ( element-type(in collection) local-variable : collection-object ) - // still use iterator internally - for(Object obj: col1){ - System.out.println(obj); - } + @Test + public void test1() { + + Collection col1 = new ArrayList(); + col1.add(123); + col1.add(456); + col1.add(789); + col1.add("yooooo"); + col1.add("kate"); + col1.add(new Person("kyo", 19)); + col1.add(false); + + // for ( element-type(in collection) local-variable : collection-object ) + // still use iterator internally + for (Object obj : col1) { + System.out.println(obj); } + } - @Test - public void test2(){ + @Test + public void test2() { - int[] arr = new int[]{1,2,3,4,5}; - // for (element-type local-variable: array-object) - for (int i : arr){ - System.out.println(i); - } + int[] arr = new int[] {1, 2, 3, 4, 5}; + // for (element-type local-variable: array-object) + for (int i : arr) { + System.out.println(i); } + } - @Test - public void test3(){ + @Test + public void test3() { - String[] arr = new String[]{"aa","aa","aa"}; - String[] arr2 = new String[]{"aa","aa","aa"}; + String[] arr = new String[] {"aa", "aa", "aa"}; + String[] arr2 = new String[] {"aa", "aa", "aa"}; - // method 1 : dispense value via basic for loop - for (int i = 0; i < arr.length; i++){ - arr[i] = "AA"; - } + // method 1 : dispense value via basic for loop + for (int i = 0; i < arr.length; i++) { + arr[i] = "AA"; + } - for (int i = 0; i < arr.length; i++){ - System.out.println(arr[i]); // "AA", since we dispense value to array element itself - } + for (int i = 0; i < arr.length; i++) { + System.out.println(arr[i]); // "AA", since we dispense value to array element itself + } - System.out.println("-----------------"); + System.out.println("-----------------"); - // method 2 - for (String s: arr2){ - s = "AA"; - } + // method 2 + for (String s : arr2) { + s = "AA"; + } - for (int i = 0; i < arr2.length; i++){ - System.out.println(arr2[i]); // still "aa", since we dispense value (AA) to local variable we extract, but not array element itself - } + for (int i = 0; i < arr2.length; i++) { + System.out.println( + arr2[ + i]); // still "aa", since we dispense value (AA) to local variable we extract, but not + // array element itself } + } } diff --git a/src/main/java/Advances/Collections/demo1.java b/src/main/java/Advances/Collections/demo1.java index 98f84875..dcbf17f3 100644 --- a/src/main/java/Advances/Collections/demo1.java +++ b/src/main/java/Advances/Collections/demo1.java @@ -2,12 +2,11 @@ // https://www.youtube.com/watch?v=ATfSTvS60Gg&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=558 -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import org.junit.jupiter.api.Test; /** * Collections demo 1 diff --git a/src/main/java/Advances/ComparableComparator/demo1.java b/src/main/java/Advances/ComparableComparator/demo1.java index 38849285..f08e7f33 100644 --- a/src/main/java/Advances/ComparableComparator/demo1.java +++ b/src/main/java/Advances/ComparableComparator/demo1.java @@ -5,137 +5,145 @@ // https://www.youtube.com/watch?v=PArFjm04xkg&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=492 /** - * Comparable Comparator demo1 + * Comparable Comparator demo1 * - * 1) default in Java, we can only do `==` or `!=`, but not `>` or `<`. - * . However, in some cases, we need to ordering (compare) the instances. - * -> `Comparable`, and `Comparator` are the interface for that + *

1) default in Java, we can only do `==` or `!=`, but not `>` or `<`. . However, in some cases, + * we need to ordering (compare) the instances. -> `Comparable`, and `Comparator` are the interface + * for that * - * 2) Comparable interface demo (natural ordering) + *

2) Comparable interface demo (natural ordering) * - * 2-1) String implements Comparable interface, override compareTo() method - * -> so it can compare instances (> or <) + *

2-1) String implements Comparable interface, override compareTo() method -> so it can compare + * instances (> or <) * - * 2-2) String, wrapper class' override compareTo() - * -> will return smallest -> biggest + *

2-2) String, wrapper class' override compareTo() -> will return smallest -> biggest * - * 2-3) String, wrapper class' override compareTo() rules: - * -> if current instance (this.xxx) > obj : return positive int - * -> if current instance (this.xxx) < obj : return negative int - * -> if current instance (this.xxx) < obj : return 0 + *

2-3) String, wrapper class' override compareTo() rules: -> if current instance (this.xxx) > + * obj : return positive int -> if current instance (this.xxx) < obj : return negative int -> if + * current instance (this.xxx) < obj : return 0 * - * 2-4) For user-defined class, if we need to ordering it, - * -> we need to implement Comparable interface, override compareTo(obj) method - * -> we need to implement `how to sorting` logic in compareTo(obj) + *

2-4) For user-defined class, if we need to ordering it, -> we need to implement Comparable + * interface, override compareTo(obj) method -> we need to implement `how to sorting` logic in + * compareTo(obj) * - * 3) Comparator interface (custom ordering) + *

3) Comparator interface (custom ordering) * - * 3-1) use case : - * 3-3-1) when the class hasn't implemented Comparable interface, and it's hard to modify the code - * 3-3-2) when current implemented Comparable not fit our requirement - * -> we can consider use Comparator + *

3-1) use case : 3-3-1) when the class hasn't implemented Comparable interface, and it's hard + * to modify the code 3-3-2) when current implemented Comparable not fit our requirement -> we can + * consider use Comparator * - * 3-2) override compare(Object o1, Object o2) - * -> compare o1, o2 - * -> if o1 > o2 : return positive int - * -> if o1 < o2 : return negative int - * -> if o1 == o2 : return 0 + *

3-2) override compare(Object o1, Object o2) -> compare o1, o2 -> if o1 > o2 : return positive + * int -> if o1 < o2 : return negative int -> if o1 == o2 : return 0 * - * 4) Comparable VS Comparator + *

4) Comparable VS Comparator * - * -> Comparable implementation can be used in any place (once defined) - * -> Comparator can only being used in that temperate place + *

-> Comparable implementation can be used in any place (once defined) -> Comparator can only + * being used in that temperate place */ - import java.util.Arrays; import java.util.Comparator; import org.junit.jupiter.api.Test; public class demo1 { - @Test - public void demo1(){ - - /** Ordering string array */ - String[] arr1 = new String[]{"dd","aa","cc","bb"}; - Arrays.sort(arr1); - - System.out.println(Arrays.toString(arr1)); // [aa, bb, cc, dd] - } - - @Test - public void demo2(){ - - /** Ordering customized class (Goods class) (Advances.ComparableComparator.Goods.java) */ - Goods[] arr = new Goods[4]; - arr[0] = new Goods("iphone", 1000); - arr[1] = new Goods("pixel", 800); - arr[2] = new Goods("x11", 200); - arr[3] = new Goods("samsung", 100); - - System.out.println(Arrays.toString(arr)); // [Good{name='iphone', price=1000.0}, Good{name='pixel', price=800.0}, Good{name='x11', price=200.0}, Good{name='samsung', price=100.0}] - - // sort - // if not implement Comparable or Comparator, then will face `java.lang.ClassCastException: class Advances.ComparableComparator.Goods cannot be cast to class java.lang.Comparable (Advances.ComparableComparator.Goods is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')` error - Arrays.sort(arr); - - System.out.println(Arrays.toString(arr)); // [Good{name='samsung', price=100.0}, Good{name='x11', price=200.0}, Good{name='pixel', price=800.0}, Good{name='iphone', price=1000.0}] - } - - @Test - public void demo3(){ - - /** Comparator example : string Array */ - String[] arr1 = new String[]{"dd","aa","cc","bb"}; - - System.out.println(Arrays.toString(arr1)); - - // ordering string from big to small - Arrays.sort(arr1, new Comparator() { - @Override - public int compare(Object o1, Object o2) { - if (o1 instanceof String && o2 instanceof String){ - String s1 = (String) o1; - String s2 = (String) o2; - return -1 * s1.compareTo(s2); - } - // *** NOTE this we throw, but not return - throw new RuntimeException("input type mismatch!"); + @Test + public void demo1() { + + /** Ordering string array */ + String[] arr1 = new String[] {"dd", "aa", "cc", "bb"}; + Arrays.sort(arr1); + + System.out.println(Arrays.toString(arr1)); // [aa, bb, cc, dd] + } + + @Test + public void demo2() { + + /** Ordering customized class (Goods class) (Advances.ComparableComparator.Goods.java) */ + Goods[] arr = new Goods[4]; + arr[0] = new Goods("iphone", 1000); + arr[1] = new Goods("pixel", 800); + arr[2] = new Goods("x11", 200); + arr[3] = new Goods("samsung", 100); + + System.out.println( + Arrays.toString( + arr)); // [Good{name='iphone', price=1000.0}, Good{name='pixel', price=800.0}, + // Good{name='x11', price=200.0}, Good{name='samsung', price=100.0}] + + // sort + // if not implement Comparable or Comparator, then will face `java.lang.ClassCastException: + // class Advances.ComparableComparator.Goods cannot be cast to class java.lang.Comparable + // (Advances.ComparableComparator.Goods is in unnamed module of loader 'app'; + // java.lang.Comparable is in module java.base of loader 'bootstrap')` error + Arrays.sort(arr); + + System.out.println( + Arrays.toString( + arr)); // [Good{name='samsung', price=100.0}, Good{name='x11', price=200.0}, + // Good{name='pixel', price=800.0}, Good{name='iphone', price=1000.0}] + } + + @Test + public void demo3() { + + /** Comparator example : string Array */ + String[] arr1 = new String[] {"dd", "aa", "cc", "bb"}; + + System.out.println(Arrays.toString(arr1)); + + // ordering string from big to small + Arrays.sort( + arr1, + new Comparator() { + @Override + public int compare(Object o1, Object o2) { + if (o1 instanceof String && o2 instanceof String) { + String s1 = (String) o1; + String s2 = (String) o2; + return -1 * s1.compareTo(s2); } + // *** NOTE this we throw, but not return + throw new RuntimeException("input type mismatch!"); + } }); - System.out.println(Arrays.toString(arr1)); // [dd, cc, bb, aa] - } - - @Test - public void demo4(){ - - /** Comparator example : user-defined class */ - - Goods[] arr = new Goods[4]; - arr[0] = new Goods("iphone", 1000); - arr[1] = new Goods("pixel", 800); - arr[2] = new Goods("x11", 200); - arr[3] = new Goods("samsung", 100); - - System.out.println(Arrays.toString(arr)); // [Good{name='iphone', price=1000.0}, Good{name='pixel', price=800.0}, Good{name='x11', price=200.0}, Good{name='samsung', price=100.0}] - - Arrays.sort(arr, new Comparator() { - // ordering by name (low->high), then price (high->low) - @Override - public int compare(Object o1, Object o2) { - if (o1 instanceof Goods && o2 instanceof Goods){ - Goods g1 = (Goods) o1; - Goods g2 = (Goods) o2; - if (g1.getName().equals(g2.getName())){ - return -1 * Double.compare(g1.getPrice(), g2.getPrice()); - }else{ - return g1.getName().compareTo(g2.getName()); - } - } - // *** NOTE this we throw, but not return - throw new RuntimeException("input type mismatch !"); + System.out.println(Arrays.toString(arr1)); // [dd, cc, bb, aa] + } + + @Test + public void demo4() { + + /** Comparator example : user-defined class */ + Goods[] arr = new Goods[4]; + arr[0] = new Goods("iphone", 1000); + arr[1] = new Goods("pixel", 800); + arr[2] = new Goods("x11", 200); + arr[3] = new Goods("samsung", 100); + + System.out.println( + Arrays.toString( + arr)); // [Good{name='iphone', price=1000.0}, Good{name='pixel', price=800.0}, + // Good{name='x11', price=200.0}, Good{name='samsung', price=100.0}] + + Arrays.sort( + arr, + new Comparator() { + // ordering by name (low->high), then price (high->low) + @Override + public int compare(Object o1, Object o2) { + if (o1 instanceof Goods && o2 instanceof Goods) { + Goods g1 = (Goods) o1; + Goods g2 = (Goods) o2; + if (g1.getName().equals(g2.getName())) { + return -1 * Double.compare(g1.getPrice(), g2.getPrice()); + } else { + return g1.getName().compareTo(g2.getName()); + } } + // *** NOTE this we throw, but not return + throw new RuntimeException("input type mismatch !"); + } }); - System.out.println(Arrays.toString((arr))); - } + System.out.println(Arrays.toString((arr))); + } } diff --git a/src/main/java/Advances/DateTimeApi/demo1.java b/src/main/java/Advances/DateTimeApi/demo1.java index 0e356643..cbe31c9d 100644 --- a/src/main/java/Advances/DateTimeApi/demo1.java +++ b/src/main/java/Advances/DateTimeApi/demo1.java @@ -7,9 +7,8 @@ * DateTimeApi demo1 : DateTime API before JDK 8 1) System.currentTimeTimeMillis(); 2) * java.util.Date and its sub class java.sql.Date 3) SimpleDateFormat 4) Calendar */ -import org.junit.jupiter.api.Test; - import java.util.Date; +import org.junit.jupiter.api.Test; public class demo1 { @@ -39,7 +38,7 @@ public void test2() { // constructor1 : Date() // -> create an Date() instance of CURRENT TIME Date date1 = new Date(); // java.util.Date - System.out.println(date1.toString()); // Sun Nov 07 08:21:46 CST 2021 + System.out.println(date1); // Sun Nov 07 08:21:46 CST 2021 System.out.println(date1.getTime()); // 1636244580892 (milliSecond) System.out.println("================"); @@ -47,7 +46,7 @@ public void test2() { // constructor2 : Date(year, month, date, hr, min) (this constructor is depreciated) // -> create an Date() instance with year, month, date, hr, min Date date2 = new Date(2021, 11, 01, 01, 00); - System.out.println(date2.toString()); // Thu Dec 01 01:00:00 CST 3921 + System.out.println(date2); // Thu Dec 01 01:00:00 CST 3921 System.out.println(date2.getTime()); // 61596435600000 (milliSecond) System.out.println("================"); @@ -55,7 +54,7 @@ public void test2() { // constructor3 : Date(someTimeStamp) // -> create an Date() instance of `given timestamp` Date date3 = new Date(1636244580892L); - System.out.println(date3.toString()); // Sun Nov 07 08:23:00 CST 2021 + System.out.println(date3); // Sun Nov 07 08:23:00 CST 2021 System.out.println(date3.getTime()); // 1636244580892 (milliSecond) } @@ -64,7 +63,7 @@ public void test2() { public void test3() { // create a java.sql.Date object java.sql.Date sql_date1 = new java.sql.Date(1636244580892L); - System.out.println(sql_date1.toString()); // 2021-11-07 + System.out.println(sql_date1); // 2021-11-07 System.out.println(sql_date1.getTime()); // 1636244580892 System.out.println("================"); diff --git a/src/main/java/Advances/DateTimeApi/demo2.java b/src/main/java/Advances/DateTimeApi/demo2.java index 96848a0b..75ee3a6e 100644 --- a/src/main/java/Advances/DateTimeApi/demo2.java +++ b/src/main/java/Advances/DateTimeApi/demo2.java @@ -25,7 +25,7 @@ public class demo2 { public void test1() throws ParseException { // we need this ParseException, since defined format/parse pattern may be - // wrong + // wrong // instantiation SimpleDateFormat sdf = new SimpleDateFormat(); diff --git a/src/main/java/Advances/DateTimeApi/demo3.java b/src/main/java/Advances/DateTimeApi/demo3.java index 39cbc234..490248d6 100644 --- a/src/main/java/Advances/DateTimeApi/demo3.java +++ b/src/main/java/Advances/DateTimeApi/demo3.java @@ -3,11 +3,10 @@ // https://www.youtube.com/watch?v=Zbr_gOK-3Go&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=480 /** DateTimeApi demo3 : String -> java.sql.Date (transform "2021-01-01" to java.sql.Date) */ -import org.junit.jupiter.api.Test; - import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; +import org.junit.jupiter.api.Test; public class demo3 { diff --git a/src/main/java/Advances/DateTimeFormatterApi/demo1.java b/src/main/java/Advances/DateTimeFormatterApi/demo1.java index 242b7cfd..0ffde566 100644 --- a/src/main/java/Advances/DateTimeFormatterApi/demo1.java +++ b/src/main/java/Advances/DateTimeFormatterApi/demo1.java @@ -10,14 +10,12 @@ * ofLocalizeDateTime (FormatStyle.Long. FormatStyle.MEDIUM, FormatStyle.SHORT) 3-3) user-defined * (common usage) : e.g. : offPattern("yyyy-mm-dd") */ -import org.junit.jupiter.api.Test; - import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; -import java.time.temporal.Temporal; import java.time.temporal.TemporalAccessor; +import org.junit.jupiter.api.Test; public class demo1 { @Test diff --git a/src/main/java/Advances/DynamicProxy/StaticProxyDemo1.java b/src/main/java/Advances/DynamicProxy/StaticProxyDemo1.java index 4e96d85c..b70e8ff6 100644 --- a/src/main/java/Advances/DynamicProxy/StaticProxyDemo1.java +++ b/src/main/java/Advances/DynamicProxy/StaticProxyDemo1.java @@ -18,7 +18,7 @@ interface ClothFactory { /** proxy class (代理類) */ class ProxyClothFactory implements ClothFactory { - private ClothFactory factory; // init instance with proxied class (e.g. ClothFactory) + private final ClothFactory factory; // init instance with proxied class (e.g. ClothFactory) // constructor public ProxyClothFactory(ClothFactory factory) { diff --git a/src/main/java/Advances/DynamicProxy/StaticProxyDemo2.java b/src/main/java/Advances/DynamicProxy/StaticProxyDemo2.java index 5c2d5741..68fc543f 100644 --- a/src/main/java/Advances/DynamicProxy/StaticProxyDemo2.java +++ b/src/main/java/Advances/DynamicProxy/StaticProxyDemo2.java @@ -16,9 +16,8 @@ class MyThread implements Runnable { @Override public void run() {} } - ; - // proxy class + // proxy class class Thread implements Runnable { public Thread(MyThread t) {} diff --git a/src/main/java/Advances/Enumeration/demo1.java b/src/main/java/Advances/Enumeration/demo1.java index 57251bde..5f6c3b1e 100644 --- a/src/main/java/Advances/Enumeration/demo1.java +++ b/src/main/java/Advances/Enumeration/demo1.java @@ -64,6 +64,7 @@ class Season { // step 1) declare Season object's attr, and make it private final private final String seasonName; private final String seasonDesc; + // constructor // step 2) make constructor private, and give attr value private Season(String seasonName, String seasonDesc) { diff --git a/src/main/java/Advances/Enumeration/demo2.java b/src/main/java/Advances/Enumeration/demo2.java index a9aee825..ba3be754 100644 --- a/src/main/java/Advances/Enumeration/demo2.java +++ b/src/main/java/Advances/Enumeration/demo2.java @@ -23,7 +23,7 @@ enum Season1 { // constructor // step 3) make constructor private, and give attr value - private Season1(String seasonName, String seasonDesc) { + Season1(String seasonName, String seasonDesc) { this.seasonName = seasonName; this.seasonDesc = seasonDesc; } @@ -98,6 +98,6 @@ public static void main(String[] args) { System.out.println("=================="); // toString() - System.out.println(summer.toString()); + System.out.println(summer); } } diff --git a/src/main/java/Advances/Enumeration/demo3.java b/src/main/java/Advances/Enumeration/demo3.java index c3cb57f9..84904d97 100644 --- a/src/main/java/Advances/Enumeration/demo3.java +++ b/src/main/java/Advances/Enumeration/demo3.java @@ -37,7 +37,7 @@ public void show() { private final String seasonDesc; // constructor - private Season2(String seasonName, String seasonDesc) { + Season2(String seasonName, String seasonDesc) { this.seasonName = seasonName; this.seasonDesc = seasonDesc; } diff --git a/src/main/java/Advances/Enumeration/demo4.java b/src/main/java/Advances/Enumeration/demo4.java index 3b8c3596..c899992c 100644 --- a/src/main/java/Advances/Enumeration/demo4.java +++ b/src/main/java/Advances/Enumeration/demo4.java @@ -54,11 +54,11 @@ public enum Color1 { YELLOW("黃色", 4); // 成員變量 - private String name; - private int index; + private final String name; + private final int index; // 構造方法 - private Color1(String name, int index) { + Color1(String name, int index) { this.name = name; this.index = index; } @@ -75,10 +75,10 @@ public enum Car { Bmw("BMW", "bmw"), Tesla("TESLA", "tesla"); - private String nominalName; - private String name; + private final String nominalName; + private final String name; - private Car(String nominalName, String name) { + Car(String nominalName, String name) { this.nominalName = nominalName; this.name = name; } diff --git a/src/main/java/Advances/Enumeration/demo5.java b/src/main/java/Advances/Enumeration/demo5.java index dac5c832..bb0d0567 100644 --- a/src/main/java/Advances/Enumeration/demo5.java +++ b/src/main/java/Advances/Enumeration/demo5.java @@ -40,11 +40,11 @@ public enum Color implements Behaviour { BLANK("白色", 3), YELLOW("黃色", 4); // 成員變量 - private String name; - private int index; + private final String name; + private final int index; // 構造方法 - private Color(String name, int index) { + Color(String name, int index) { this.name = name; this.index = index; } diff --git a/src/main/java/Advances/FileIO/demo1.java b/src/main/java/Advances/FileIO/demo1.java index e856a226..58ee6bc4 100644 --- a/src/main/java/Advances/FileIO/demo1.java +++ b/src/main/java/Advances/FileIO/demo1.java @@ -6,38 +6,38 @@ import java.io.File; import org.junit.jupiter.api.Test; -/** File IO demo 1 : File class +/** + * File IO demo 1 : File class * - * 1) File class object : represents a doc or doc path (file) - * 2) File class is under java.io class - * 3) File class can do file/file path create, delete, rename, modified time, file size... - * -> BUT CAN'T read or write File - * -> if we want read or write File -> need to use IO flow - * 4) File class will be used as "parameter" and passed to IO flow as read, write "end point" + *

1) File class object : represents a doc or doc path (file) 2) File class is under java.io + * class 3) File class can do file/file path create, delete, rename, modified time, file size... -> + * BUT CAN'T read or write File -> if we want read or write File -> need to use IO flow 4) File + * class will be used as "parameter" and passed to IO flow as read, write "end point" */ - public class demo1 { - /** test1 : - * - * 1) how to create file class instance - * 2) relative VS absolute path - */ - @Test - public void test1(){ - // constructor 1 - File file = new File("hello.txt"); // relative path (current module) - File file2 = new File("/Users/yennanliu/JavaHelloWorld/src/main/java/Advances/FileIO/Hungry.java"); // absolute path - - System.out.println(file); - System.out.println(file2); - - // constructor 2 - File file3 = new File("/JavaHelloWorld/src/main/java/Advances", "FileIO"); // parent, child - System.out.println(file3); - - // constructor 3 - File file4 = new File(file3,"hi.txt"); - System.out.println(file4); - } + /** + * test1 : + * + *

1) how to create file class instance 2) relative VS absolute path + */ + @Test + public void test1() { + // constructor 1 + File file = new File("hello.txt"); // relative path (current module) + File file2 = + new File( + "/Users/yennanliu/JavaHelloWorld/src/main/java/Advances/FileIO/Hungry.java"); // absolute path + + System.out.println(file); + System.out.println(file2); + + // constructor 2 + File file3 = new File("/JavaHelloWorld/src/main/java/Advances", "FileIO"); // parent, child + System.out.println(file3); + + // constructor 3 + File file4 = new File(file3, "hi.txt"); + System.out.println(file4); + } } diff --git a/src/main/java/Advances/FileIO/demo2.java b/src/main/java/Advances/FileIO/demo2.java index 5fef2baa..4a5fcd7b 100644 --- a/src/main/java/Advances/FileIO/demo2.java +++ b/src/main/java/Advances/FileIO/demo2.java @@ -3,11 +3,10 @@ // https://www.youtube.com/watch?v=4d426JMTXhc&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=577 // https://www.youtube.com/watch?v=mPFq9hUP74c&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=578 -import org.junit.jupiter.api.Test; - import java.io.File; import java.io.IOException; import java.util.Date; +import org.junit.jupiter.api.Test; /** File IO demo 2 : File common methods */ public class demo2 { @@ -49,9 +48,8 @@ public void test2() { File[] files = file.listFiles(); for (File f : files) { - System.out.println( - f); // absolute path : e.g. - // /Users/yennanliu/JavaHelloWorld/src/main/java/Advances/InstantApi ... + System.out.println(f); // absolute path : e.g. + // /Users/yennanliu/JavaHelloWorld/src/main/java/Advances/InstantApi ... } } diff --git a/src/main/java/Advances/FileIO/demo3.java b/src/main/java/Advances/FileIO/demo3.java index da89689f..f521f426 100644 --- a/src/main/java/Advances/FileIO/demo3.java +++ b/src/main/java/Advances/FileIO/demo3.java @@ -8,55 +8,55 @@ public class demo3 { - // help func - public static void printSubFile(File dir){ - // print sub files - File[] subfiles = dir.listFiles(); - - for (File f: subfiles){ - if (f.isDirectory()){ // if directory - printSubFile(f); - }else{ // if file - System.out.println(f.getAbsolutePath()); - } - } + // help func + public static void printSubFile(File dir) { + // print sub files + File[] subfiles = dir.listFiles(); + + for (File f : subfiles) { + if (f.isDirectory()) { // if directory + printSubFile(f); + } else { // if file + System.out.println(f.getAbsolutePath()); + } } + } - @Test - public void test1() throws IOException { - File file = new File("hello.txt"); - File destFile = new File(file.getParent(), "hello2.txt"); - boolean newFile = destFile.createNewFile(); + @Test + public void test1() throws IOException { + File file = new File("hello.txt"); + File destFile = new File(file.getParent(), "hello2.txt"); + boolean newFile = destFile.createNewFile(); - if(newFile){ - System.out.println("crate file OK"); - } + if (newFile) { + System.out.println("crate file OK"); } - - @Test - public void test2(){ - File dir = new File("/Users/yennanliu/JavaHelloWorld/src/main/java/Advances"); - printSubFile(dir); - } - - @Test - public void test3(){ - // if we want to delete path, there MUST be NO files, sub paths under it - File file = new File("hello2.txt"); - System.out.println(file.delete()); - } - - public void deleteDirectory(File file){ - // if file is file, then delete - // if file is a path, then NEED to delete all its sub files/paths, then delete the current path - if (file.isDirectory()) { - File[] all = file.listFiles(); - // for loop and delete path/file in next level - for (File f: all){ - deleteDirectory(f); - } - } - // delete current path - file.delete(); + } + + @Test + public void test2() { + File dir = new File("/Users/yennanliu/JavaHelloWorld/src/main/java/Advances"); + printSubFile(dir); + } + + @Test + public void test3() { + // if we want to delete path, there MUST be NO files, sub paths under it + File file = new File("hello2.txt"); + System.out.println(file.delete()); + } + + public void deleteDirectory(File file) { + // if file is file, then delete + // if file is a path, then NEED to delete all its sub files/paths, then delete the current path + if (file.isDirectory()) { + File[] all = file.listFiles(); + // for loop and delete path/file in next level + for (File f : all) { + deleteDirectory(f); + } } + // delete current path + file.delete(); + } } diff --git a/src/main/java/Advances/Generic/demo1.java b/src/main/java/Advances/Generic/demo1.java index 82e54aee..140d506b 100644 --- a/src/main/java/Advances/Generic/demo1.java +++ b/src/main/java/Advances/Generic/demo1.java @@ -5,96 +5,95 @@ // https://www.youtube.com/watch?v=kRiy9mS2B9A&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=567 /** - * Generic demo 1 + * Generic demo 1 * - * 1) since JDK 5.0 + *

1) since JDK 5.0 * - * 2) use Generic in collections - * -> 2.1) Interface are all in "Generic version" since JDK 5.0 - * -> 2.2) we can define generic type when initialize collection class - * -> 2.3) after initialize class with generic type, - * -> ALL internal structure/val are with SAME generic type - * -> w.g. add(E e) --initialize--> add (Integer e) - * -> 2.4) Generic type myst be a "Class" (can't use basic type (e.g. int, float)) - * -> 2.5) if NOT use generic when initialize, will use default type : java.Lang.Object + *

2) use Generic in collections -> 2.1) Interface are all in "Generic version" since JDK 5.0 -> + * 2.2) we can define generic type when initialize collection class -> 2.3) after initialize class + * with generic type, -> ALL internal structure/val are with SAME generic type -> w.g. add(E e) + * --initialize--> add (Integer e) -> 2.4) Generic type myst be a "Class" (can't use basic type + * (e.g. int, float)) -> 2.5) if NOT use generic when initialize, will use default type : + * java.Lang.Object * - * 3) define custom generic type - * -> 2.1) generic class, generic interface, generic method - * -> Advances.Generic.demo3.java + *

3) define custom generic type -> 2.1) generic class, generic interface, generic method -> + * Advances.Generic.demo3.java * - * 4) generic type CAN'T be used in static class - * - but generic type CAN be used in static method - * - copyFromArrayList method in Advances.Generic.Order class - * 5) generic type CAN'T be used in exception class + *

4) generic type CAN'T be used in static class - but generic type CAN be used in static method + * - copyFromArrayList method in Advances.Generic.Order class 5) generic type CAN'T be used in + * exception class */ - import java.util.*; import org.junit.jupiter.api.Test; public class demo1 { - @Test - public void test1(){ - ArrayList list1 = new ArrayList(); + @Test + public void test1() { + ArrayList list1 = new ArrayList(); - list1.add(10); - list1.add(75); - list1.add(87); - //list1.add("tom"); // problem 1 : type unsafe + list1.add(10); + list1.add(75); + list1.add(87); + // list1.add("tom"); // problem 1 : type unsafe - for (Object score: list1){ - // problem 2 : java.lang.ClassCastException may happen when Downcasting - // -> e.g. :java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap') - int stuScore = (Integer) score; - System.out.println(score); - } + for (Object score : list1) { + // problem 2 : java.lang.ClassCastException may happen when Downcasting + // -> e.g. :java.lang.ClassCastException: class java.lang.String cannot be cast to + // class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of + // loader 'bootstrap') + int stuScore = (Integer) score; + System.out.println(score); } + } - /** Generic demo 1 */ - @Test - public void test2(){ - ArrayList list1 = new ArrayList(); - //ArrayList list1 = new ArrayList(); // can't use "basic type" as generic. e.g. : Type argument cannot be of primitive type + /** Generic demo 1 */ + @Test + public void test2() { + ArrayList list1 = new ArrayList(); + // ArrayList list1 = new ArrayList(); // can't use "basic type" as generic. e.g. : Type + // argument cannot be of primitive type - list1.add(10); - list1.add(75); - list1.add(87); - //list1.add("tom"); // this one can't even pass compile, since we already used generic type ( ArrayList list1 = new ArrayList();) + list1.add(10); + list1.add(75); + list1.add(87); + // list1.add("tom"); // this one can't even pass compile, since we already used generic type ( + // ArrayList list1 = new ArrayList();) - // loop 1 - for (Object score: list1){ - // Downcasting is not needed anymore - //int stuScore = (Integer) score; - System.out.println(score); - } + // loop 1 + for (Object score : list1) { + // Downcasting is not needed anymore + // int stuScore = (Integer) score; + System.out.println(score); + } - System.out.println("=================="); + System.out.println("=================="); - // loop2 - Iterator iterator1 = list1.iterator(); - while (iterator1.hasNext()){ - int stuScore = iterator1.next(); - System.out.println(stuScore); - } + // loop2 + Iterator iterator1 = list1.iterator(); + while (iterator1.hasNext()) { + int stuScore = iterator1.next(); + System.out.println(stuScore); } + } - @Test - public void test3(){ - Map map1 = new HashMap(); + @Test + public void test3() { + Map map1 = new HashMap(); - map1.put("a",123); - map1.put("b",777); - map1.put("c",544); - map1.put("d",665); + map1.put("a", 123); + map1.put("b", 777); + map1.put("c", 544); + map1.put("d", 665); - // loop1 - // Map's entry is > type - Set > entry1 = map1.entrySet(); - Iterator> iterator1 = entry1.iterator(); - while (iterator1.hasNext()){ - Map.Entry e = iterator1.next(); - String key = e.getKey(); - Integer value = e.getValue(); - System.out.println(key + "----> " + value); - } + // loop1 + // Map's entry is > type + Set> entry1 = map1.entrySet(); + Iterator> iterator1 = entry1.iterator(); + while (iterator1.hasNext()) { + Map.Entry e = iterator1.next(); + String key = e.getKey(); + Integer value = e.getValue(); + System.out.println(key + "----> " + value); } + } } diff --git a/src/main/java/Advances/Generic/demo2.java b/src/main/java/Advances/Generic/demo2.java index 2c0d4588..b30feaf0 100644 --- a/src/main/java/Advances/Generic/demo2.java +++ b/src/main/java/Advances/Generic/demo2.java @@ -3,11 +3,10 @@ // https://www.youtube.com/watch?v=cgsQbgB5egA&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=566 /** demo2 : generic type to custom class, work with custom/natural ordering */ -import org.junit.jupiter.api.Test; - import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet; +import org.junit.jupiter.api.Test; public class demo2 { diff --git a/src/main/java/Advances/Generic/demo3.java b/src/main/java/Advances/Generic/demo3.java index b9b29928..a7aed43e 100644 --- a/src/main/java/Advances/Generic/demo3.java +++ b/src/main/java/Advances/Generic/demo3.java @@ -4,58 +4,58 @@ // https://www.youtube.com/watch?v=ilutsOhRmuk&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=568 /** demo3 : generic class, generic interface, generic method */ - import Advances.CollectionDemo.Person; import java.util.ArrayList; import org.junit.jupiter.api.Test; public class demo3 { - @Test - public void test1(){ - // will assume type as "object" if already defined generic type in class, - // but not use it (generic type) when instantiate - // (not recommended) - Order order = new Order(); - order.setOrderT(123); - order.setOrderT("abc"); - - } - - @Test - public void test2(){ - // instantiate with generic type - // (recommended) - Order order = new Order("orderAA",1001,"oder:AA"); - //order.setOrderT(123); - order.setOrderT("123"); - order.setOrderT("abc"); - } - - @Test - public void test3(){ - // since we already defined generic type when define SubOrder - // so it's NO NEEDED to define generic type when instantiate the class (subOrder) - SubOrder sub1 = new SubOrder(); - sub1.setOrderT(123); - sub1.setOrderT(456); - - SubOrder2 sub2 = new SubOrder2<>(); // type inference (either new SubOrder2() or new SubOrder2<>() is OK) - sub2.setOrderT("abc"); - sub2.setOrderT("xyz"); - } - - @Test - public void test4(){ - ArrayList list1 = null; - ArrayList list2 = null; - - // CAN'T assign different generic type reference to each other - //list1 = list2; - - // comare - Person p1 = null; - Person p2 = null; - - p1 = p2; - } + @Test + public void test1() { + // will assume type as "object" if already defined generic type in class, + // but not use it (generic type) when instantiate + // (not recommended) + Order order = new Order(); + order.setOrderT(123); + order.setOrderT("abc"); + } + + @Test + public void test2() { + // instantiate with generic type + // (recommended) + Order order = new Order("orderAA", 1001, "oder:AA"); + // order.setOrderT(123); + order.setOrderT("123"); + order.setOrderT("abc"); + } + + @Test + public void test3() { + // since we already defined generic type when define SubOrder + // so it's NO NEEDED to define generic type when instantiate the class (subOrder) + SubOrder sub1 = new SubOrder(); + sub1.setOrderT(123); + sub1.setOrderT(456); + + SubOrder2 sub2 = + new SubOrder2<>(); // type inference (either new SubOrder2() or new SubOrder2<>() is + // OK) + sub2.setOrderT("abc"); + sub2.setOrderT("xyz"); + } + + @Test + public void test4() { + ArrayList list1 = null; + ArrayList list2 = null; + + // CAN'T assign different generic type reference to each other + // list1 = list2; + + // comare + Person p1 = null; + Person p2 = null; + + p1 = p2; + } } diff --git a/src/main/java/Advances/Generic/demo4.java b/src/main/java/Advances/Generic/demo4.java index b1d10572..d4034cbc 100644 --- a/src/main/java/Advances/Generic/demo4.java +++ b/src/main/java/Advances/Generic/demo4.java @@ -3,18 +3,17 @@ // https://www.youtube.com/watch?v=Lws0GkOTckQ&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=569 /** demo4 : generic method */ - import java.util.List; import org.junit.jupiter.api.Test; public class demo4 { - @Test - public void test1(){ - Order order = new Order<>(); - Integer[] arr = new Integer[]{1,2,3,4}; - // call generic method, and define its attr with generic type - List list = order.copyFromArrayList(arr); + @Test + public void test1() { + Order order = new Order<>(); + Integer[] arr = new Integer[] {1, 2, 3, 4}; + // call generic method, and define its attr with generic type + List list = order.copyFromArrayList(arr); - System.out.println(list); - } + System.out.println(list); + } } diff --git a/src/main/java/Advances/Generic/demo5.java b/src/main/java/Advances/Generic/demo5.java index bd43241c..84250461 100644 --- a/src/main/java/Advances/Generic/demo5.java +++ b/src/main/java/Advances/Generic/demo5.java @@ -5,9 +5,8 @@ /** demo5 : generic example : DAO */ import Advances.Generic.dao.EmployeeDAO; import Advances.Generic.dao.StudentDAO; -import org.junit.jupiter.api.Test; - import java.util.List; +import org.junit.jupiter.api.Test; public class demo5 { @Test diff --git a/src/main/java/Advances/Generic/demo6.java b/src/main/java/Advances/Generic/demo6.java index cd5a9069..d832add8 100644 --- a/src/main/java/Advances/Generic/demo6.java +++ b/src/main/java/Advances/Generic/demo6.java @@ -4,11 +4,10 @@ // https://www.youtube.com/watch?v=_53WGmiijGA&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=572 // https://www.youtube.com/watch?v=UWwPoU_SId0&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=573 -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import org.junit.jupiter.api.Test; /** * demo6 : generic diff --git a/src/main/java/Advances/Generic/demo7.java b/src/main/java/Advances/Generic/demo7.java index a411e0f7..8eac2701 100644 --- a/src/main/java/Advances/Generic/demo7.java +++ b/src/main/java/Advances/Generic/demo7.java @@ -5,33 +5,31 @@ import java.util.List; import org.junit.jupiter.api.Test; -/** generic type with limited condition +/** + * generic type with limited condition * - * 1) ? extends A: - * -> G : can be G, and G's super class, B is A's sub class - * - * 2)? super Student2: - * -> G : can be G, and G's super class, B is A's super class + *

1) ? extends A: -> G : can be G, and G's super class, B is A's sub class * + *

2)? super Student2: -> G : can be G, and G's super class, B is A's super + * class */ public class demo7 { - @Test - public void test1(){ + @Test + public void test1() { - // extends : "<=" - List list1 = null; + // extends : "<=" + List list1 = null; - // super : ">=" - List list2 = null; + // super : ">=" + List list2 = null; - List list3 = null; - List list4 = null; - List list5 = null; + List list3 = null; + List list4 = null; + List list5 = null; - // assign values - //list1 = list3; - //list1 = list4; - //list1 = list5; - } + // assign values + // list1 = list3; + // list1 = list4; + // list1 = list5; + } } - diff --git a/src/main/java/Advances/Generic/demo8.java b/src/main/java/Advances/Generic/demo8.java index 060cd031..a0154492 100644 --- a/src/main/java/Advances/Generic/demo8.java +++ b/src/main/java/Advances/Generic/demo8.java @@ -2,7 +2,6 @@ // https://www.youtube.com/watch?v=UhgmcVG05qA&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=574 -import Advances.Generic.*; public class demo8 { public static void main(String[] args) { diff --git a/src/main/java/Advances/Generic/demo9.java b/src/main/java/Advances/Generic/demo9.java index ae5fe4a7..d4470519 100644 --- a/src/main/java/Advances/Generic/demo9.java +++ b/src/main/java/Advances/Generic/demo9.java @@ -3,40 +3,39 @@ // https://www.youtube.com/watch?v=SqqPjmtseSs&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=575 /** test for dao2.DAO */ - import Advances.Generic.dao2.*; import java.util.List; public class demo9 { - public static void main(String[] args) { - Advances.Generic.dao2.DAO dao = new Advances.Generic.dao2.DAO(); + public static void main(String[] args) { + Advances.Generic.dao2.DAO dao = new Advances.Generic.dao2.DAO(); - // save - dao.save("1001", new User(1001,20,"iori")); - dao.save("1002", new User(1002,17,"kyo")); - dao.save("1003", new User(1003,88,"mary")); + // save + dao.save("1001", new User(1001, 20, "iori")); + dao.save("1002", new User(1002, 17, "kyo")); + dao.save("1003", new User(1003, 88, "mary")); - List user = dao.list(); - // method 1 - System.out.println(user); + List user = dao.list(); + // method 1 + System.out.println(user); - System.out.println("=========="); + System.out.println("=========="); - // method 2 : forEach (new since java 8) - user.forEach(System.out::println); + // method 2 : forEach (new since java 8) + user.forEach(System.out::println); - System.out.println("=========="); + System.out.println("=========="); - // update - dao.update("1003", new User(1003, 30, "kk")); - List user2 = dao.list(); - System.out.println(user2); + // update + dao.update("1003", new User(1003, 30, "kk")); + List user2 = dao.list(); + System.out.println(user2); - System.out.println("=========="); + System.out.println("=========="); - // delete - dao.delete("1002"); - List user3 = dao.list(); - System.out.println(user3); - } + // delete + dao.delete("1002"); + List 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 dataList = new ArrayList<>(); + // List dataList = Arrays.asList(d1, d2, d3); + dataList.add(d1); + dataList.add(d2); + dataList.add(d3); - System.out.println(">>> idx = " + idx); + Integer idx = dataList.indexOf(d3); - // Initial list - System.out.println("Initial List: " + dataList); + System.out.println(">>> idx = " + idx); - // remove element - dataList.remove(idx); + // Initial list + System.out.println("Initial List: " + dataList); - // Final list - System.out.println("Final List: " + dataList); + // remove element + dataList.remove(idx); - } + // Final list + System.out.println("Final List: " + dataList); + } - @Test - public void test2_2(){ + @Test + public void test2_2() { - Data2 d1 = new Data2("1", "others", "100"); - Data2 d2 = new Data2("2", "a", "900000"); - Data2 d3 = new Data2("3", "b", "200"); - Data2 d4 = new Data2("4", "others", "70000"); - Data2 d5 = new Data2("5", "d", "300"); + Data2 d1 = new Data2("1", "others", "100"); + Data2 d2 = new Data2("2", "a", "900000"); + Data2 d3 = new Data2("3", "b", "200"); + Data2 d4 = new Data2("4", "others", "70000"); + Data2 d5 = new Data2("5", "d", "300"); - //Data[] dataList = new Data[]{d1,d4,d3,d2}; - List dataList = new ArrayList<>(); - //List dataList = Arrays.asList(d1, d2, d3); - dataList.add(d1); - dataList.add(d4); - dataList.add(d2); - dataList.add(d3); - dataList.add(d5); + // Data[] dataList = new Data[]{d1,d4,d3,d2}; + List dataList = new ArrayList<>(); + // List dataList = Arrays.asList(d1, d2, d3); + dataList.add(d1); + dataList.add(d4); + dataList.add(d2); + dataList.add(d3); + dataList.add(d5); - // Initial list - System.out.println("Initial List: " + dataList); + // Initial list + System.out.println("Initial List: " + dataList); - Collections.sort(dataList, (o1, o2)->{ - String id1 = o1.getId(); - String id2 = o2.getId(); - String type1 = o1.getType(); - String type2 = o2.getType(); - String value1 = o1.getValue(); - String value2 = o2.getValue(); - if (type1.equals("others") && !type2.equals("others")){ - return 1; - }else if(!type1.equals("others") && type2.equals("others")){ - return -1; - } else if (type1.equals("others") && type2.equals("others")) { - return 0; - } - return (int) (Double.parseDouble(value1) - Double.parseDouble(value2)); + Collections.sort( + dataList, + (o1, o2) -> { + String id1 = o1.getId(); + String id2 = o2.getId(); + String type1 = o1.getType(); + String type2 = o2.getType(); + String value1 = o1.getValue(); + String value2 = o2.getValue(); + if (type1.equals("others") && !type2.equals("others")) { + return 1; + } else if (!type1.equals("others") && type2.equals("others")) { + return -1; + } else if (type1.equals("others") && type2.equals("others")) { + return 0; + } + return (int) (Double.parseDouble(value1) - Double.parseDouble(value2)); }); - // Final list - System.out.println("Final List: " + dataList); - } - - @Test - public void test3(){ - - // https://www.digitalocean.com/community/tutorials/java-list-remove-methods-arraylist-remove + // Final list + System.out.println("Final List: " + dataList); + } - List list = new ArrayList<>(); - list.add("A"); - list.add("B"); - list.add("C"); - list.add("C"); - list.add("B"); - list.add("A"); - System.out.println(list); + @Test + public void test3() { - boolean isRemoved = list.remove("C"); - System.out.println(list); - System.out.println(isRemoved); + // https://www.digitalocean.com/community/tutorials/java-list-remove-methods-arraylist-remove - isRemoved = list.remove("X"); - System.out.println(list); - System.out.println(isRemoved); + List list = new ArrayList<>(); + list.add("A"); + list.add("B"); + list.add("C"); + list.add("C"); + list.add("B"); + list.add("A"); + System.out.println(list); - } + boolean isRemoved = list.remove("C"); + System.out.println(list); + System.out.println(isRemoved); - @Test - public void test4(){ + isRemoved = list.remove("X"); + System.out.println(list); + System.out.println(isRemoved); + } - // https://www.geeksforgeeks.org/list-removeint-index-method-in-java-with-examples/#:~:text=The%20remove(int%20index)%20method,the%20left%20in%20the%20List. + @Test + public void test4() { - List list = new ArrayList(5); + // https://www.geeksforgeeks.org/list-removeint-index-method-in-java-with-examples/#:~:text=The%20remove(int%20index)%20method,the%20left%20in%20the%20List. - // Add elements to the list - list.add(5); - list.add(10); - list.add(15); - list.add(20); - list.add(25); + List list = new ArrayList(5); - // Index from which you want to remove element - int index = 2; + // Add elements to the list + list.add(5); + list.add(10); + list.add(15); + list.add(20); + list.add(25); - // Initial list - System.out.println("Initial List: " + list); + // Index from which you want to remove element + int index = 2; - // remove element - list.remove(index); + // Initial list + System.out.println("Initial List: " + list); - // Final list - System.out.println("Final List: " + list); - } + // remove element + list.remove(index); + // Final list + System.out.println("Final List: " + list); + } } diff --git a/src/main/java/dev/FastJsonTest1.java b/src/main/java/dev/FastJsonTest1.java index 9b0ab31b..108393d1 100644 --- a/src/main/java/dev/FastJsonTest1.java +++ b/src/main/java/dev/FastJsonTest1.java @@ -4,7 +4,7 @@ // https://blog.csdn.net/xuexi_gan/article/details/114915890 // https://github.com/yennanliu/til/blob/master/README.md#20221029 -//import com.alibaba.fastjson.JSON; +// import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import dev.bean.Car; @@ -14,50 +14,53 @@ public class FastJsonTest1 { - /** - * - * // java - * Map> result = - * JSON.parseObject(CatelogJSON, new TypeReference>>() {} ); - */ - - /** - * https://www.runoob.com/w3cnote/fastjson-intro.html - * - * Java obj -> json - */ - @Test - public void JavaObj2Json1(){ - - List cars = new ArrayList(); - cars.add(new Car(1,"TESLA",1000)); - cars.add(new Car(2,"BMW",999)); - cars.add(new Car(3,"BENZ",362)); - - String jString1 = JSON.toJSONString(cars); - - System.out.println(">>> jString1 = " + jString1); // jString1 = [{"brand":"TESLA","id":1,"idAndBrand":"1-TESLA","price":1000.0},{"brand":"BMW","id":2,"idAndBrand":"2-BMW","price":999.0},{"brand":"BENZ","id":3,"idAndBrand":"3-BENZ","price":362.0}] - } + /** + * // java Map> result = JSON.parseObject(CatelogJSON, new + * TypeReference>>() {} ); + */ - @Test - public void Str2Json_1(){ - - // https://juejin.cn/post/6989067030775545886 - // https://www.w3cschool.cn/fastjson/fastjson-ex2.html - - // TODO Auto-generated method stub - //String str = "{\"cases\"[{\"classname\":\"HttpGet\",\"url\":\"https://www.baidu.com\"},{\"classname\":\"HttpPost\",\"url\":\"https:www.qq.com\"}]}"; - //String str = "{\"cases\"[{\"classname\":\"HttpGet\",\"url\":\"https://www.baidu.com\"},{\"classname\":\"HttpPost\",\"url\":\"https:www.qq.com\"}]}"; - //String str = "{\"avBar\":[{\"barAge\":174398800,\"barDate\":\"2011-11-23 23:30:33\",\"barName\":\"sss_0.62378174\"}"; - String str = "{'area':{'area':'1','pagetype':'home'},'pagetype':'home'}"; - JSONObject json; - try{ - json = JSON.parseObject(str); - System.out.println(json); - System.out.println(json.get("pagetype")); - }catch (Exception e){ - System.out.println(e); - } - } + /** + * https://www.runoob.com/w3cnote/fastjson-intro.html + * + *

Java obj -> json + */ + @Test + public void JavaObj2Json1() { + + List cars = new ArrayList(); + cars.add(new Car(1, "TESLA", 1000)); + cars.add(new Car(2, "BMW", 999)); + cars.add(new Car(3, "BENZ", 362)); + + String jString1 = JSON.toJSONString(cars); + System.out.println( + ">>> jString1 = " + + jString1); // jString1 = + // [{"brand":"TESLA","id":1,"idAndBrand":"1-TESLA","price":1000.0},{"brand":"BMW","id":2,"idAndBrand":"2-BMW","price":999.0},{"brand":"BENZ","id":3,"idAndBrand":"3-BENZ","price":362.0}] + } + + @Test + public void Str2Json_1() { + + // https://juejin.cn/post/6989067030775545886 + // https://www.w3cschool.cn/fastjson/fastjson-ex2.html + + // TODO Auto-generated method stub + // String str = + // "{\"cases\"[{\"classname\":\"HttpGet\",\"url\":\"https://www.baidu.com\"},{\"classname\":\"HttpPost\",\"url\":\"https:www.qq.com\"}]}"; + // String str = + // "{\"cases\"[{\"classname\":\"HttpGet\",\"url\":\"https://www.baidu.com\"},{\"classname\":\"HttpPost\",\"url\":\"https:www.qq.com\"}]}"; + // String str = "{\"avBar\":[{\"barAge\":174398800,\"barDate\":\"2011-11-23 + // 23:30:33\",\"barName\":\"sss_0.62378174\"}"; + String str = "{'area':{'area':'1','pagetype':'home'},'pagetype':'home'}"; + JSONObject json; + try { + json = JSON.parseObject(str); + System.out.println(json); + System.out.println(json.get("pagetype")); + } catch (Exception e) { + System.out.println(e); + } + } } diff --git a/src/main/java/dev/FileIOTest.java b/src/main/java/dev/FileIOTest.java index 4179d6c3..a70d07b0 100644 --- a/src/main/java/dev/FileIOTest.java +++ b/src/main/java/dev/FileIOTest.java @@ -7,28 +7,27 @@ public class FileIOTest { - @Test - public void test1(){ + @Test + public void test1() { - //FileUtils.writeByteArrayToFile(new File(CSV_FILE), csv_data); - } + // FileUtils.writeByteArrayToFile(new File(CSV_FILE), csv_data); + } - @Test - public void test2(){ + @Test + public void test2() { - String csvFile = "classpath:test.csv"; - //File file = new File(getClass().getResource("/test.csv").getFile()); - File file = new File(getClass().getResource("/templates/test1.ftl").getFile()); - String resources_file_path = getClass().getResource("/templates/test1.ftl").getFile(); + String csvFile = "classpath:test.csv"; + // File file = new File(getClass().getResource("/test.csv").getFile()); + File file = new File(getClass().getResource("/templates/test1.ftl").getFile()); + String resources_file_path = getClass().getResource("/templates/test1.ftl").getFile(); - IFileUtils IFileUtils = new IFileUtils(); - List> res = IFileUtils.loadCSVFile(file); + IFileUtils IFileUtils = new IFileUtils(); + List> res = IFileUtils.loadCSVFile(file); - System.out.println(">>> resources_file_path = " + resources_file_path); + System.out.println(">>> resources_file_path = " + resources_file_path); - System.out.println("============"); - - res.forEach(x -> System.out.println(x)); - } + System.out.println("============"); + res.forEach(x -> System.out.println(x)); + } } diff --git a/src/main/java/dev/FileTest.java b/src/main/java/dev/FileTest.java index de025aec..813f8193 100644 --- a/src/main/java/dev/FileTest.java +++ b/src/main/java/dev/FileTest.java @@ -7,40 +7,39 @@ public class FileTest { - @Test - public void test1(){ + @Test + public void test1() { - ArrayList files = new ArrayList<>(); - files.add("file_unzip/part-00000-92b76207-f477-48f5-a510-85dd0269ec01-c000.csv"); - files.add("file_unzip/part-00000-f8ee8e0f-deca-4beb-8d01-7696c6137a83-c000.csv"); - files.add("file_unzip/part-00000-9b9fb1b7-5464-491a-83ef-101ef112b863-c000.csv"); + ArrayList files = new ArrayList<>(); + files.add("file_unzip/part-00000-92b76207-f477-48f5-a510-85dd0269ec01-c000.csv"); + files.add("file_unzip/part-00000-f8ee8e0f-deca-4beb-8d01-7696c6137a83-c000.csv"); + files.add("file_unzip/part-00000-9b9fb1b7-5464-491a-83ef-101ef112b863-c000.csv"); - files.stream().forEach(System.out::println); + files.stream().forEach(System.out::println); - // Use String#matches (with regexp) -// result = Stream.of(strings).filter(str -> str.matches("^" + prefix + ".*$")) -// .collect(Collectors.toSet()).toArray(new String[0]); -// Stream.of(result).forEach(System.out::println); //-> adjnrj adcfd -// + // Use String#matches (with regexp) + // result = Stream.of(strings).filter(str -> str.matches("^" + prefix + ".*$")) + // .collect(Collectors.toSet()).toArray(new String[0]); + // Stream.of(result).forEach(System.out::println); //-> adjnrj adcfd + // - } - - @Test - public void test2(){ + } - String CSV_ZIP_FILE = "some_file"; - IFileUtils.deleteDirectory(new File(CSV_ZIP_FILE)); + @Test + public void test2() { - for (int i =1; i<5 ; i+=1){ - System.out.println(">>> " + i); - } - } + String CSV_ZIP_FILE = "some_file"; + IFileUtils.deleteDirectory(new File(CSV_ZIP_FILE)); - @Test - public void test3(){ - String x = "[1001]"; - String y = x.replace("[","").replace("]",""); - System.out.println(y); + for (int i = 1; i < 5; i += 1) { + System.out.println(">>> " + i); } - + } + + @Test + public void test3() { + String x = "[1001]"; + String y = x.replace("[", "").replace("]", ""); + System.out.println(y); + } } diff --git a/src/main/java/dev/ForLoopFunc.java b/src/main/java/dev/ForLoopFunc.java index 7b3621c2..6cb4ecec 100644 --- a/src/main/java/dev/ForLoopFunc.java +++ b/src/main/java/dev/ForLoopFunc.java @@ -12,7 +12,6 @@ public static void main(String[] args) { e.printStackTrace(); } } - ; } class RunForLoop { diff --git a/src/main/java/dev/IFileUtilsTest.java b/src/main/java/dev/IFileUtilsTest.java index fe45aa75..e446c59b 100644 --- a/src/main/java/dev/IFileUtilsTest.java +++ b/src/main/java/dev/IFileUtilsTest.java @@ -10,9 +10,8 @@ public class IFileUtilsTest { - @Test - public void test1(){ + public void test1() { System.out.println(123); IFileUtils fileUtils = new IFileUtils(); @@ -22,7 +21,7 @@ public void test1(){ srcFiles.add("src/main/resources/" + "test2.csv"); srcFiles.add("src/main/resources/" + "test1.txt"); - //String destZipFiles = "src/main/resources/" + "zipEncryptFile.zip"; + // String destZipFiles = "src/main/resources/" + "zipEncryptFile.zip"; String destZipFiles = "src/main/resources" + ".zip"; fileUtils.encryptFile(srcFiles, destZipFiles, "123"); } @@ -46,27 +45,25 @@ public void test3() throws IOException { FileUtils.copyFile(new File(unzipFilePath), new File(copiedFile)); files.add(copiedFile); - //files.add(copiedFile); + // files.add(copiedFile); System.out.println(">>> files = " + files); - //String encryptFileUrl = fileUtils.encryptFile(files, uploadPath + tempFile, password); + // String encryptFileUrl = fileUtils.encryptFile(files, uploadPath + tempFile, password); fileUtils.encryptFile(files, destZipFiles, "123"); } @Test - public void test4(){ - System.out.println(">>> File.separator = " + File.separator); + public void test4() { + System.out.println(">>> File.separator = " + File.separator); } - @Test public void test5() throws IOException { String srcFile = "src/main/resources/" + "test.csv"; - FileUtils.copyFileToDirectory(new File(srcFile), new File( "src/main/resources/" + "backup")); + FileUtils.copyFileToDirectory(new File(srcFile), new File("src/main/resources/" + "backup")); - //FileUtils.listFiles(new File("XXX")); + // FileUtils.listFiles(new File("XXX")); } - } diff --git a/src/main/java/dev/ParseCSVTest.java b/src/main/java/dev/ParseCSVTest.java index b899bd14..2d47c7ca 100644 --- a/src/main/java/dev/ParseCSVTest.java +++ b/src/main/java/dev/ParseCSVTest.java @@ -8,60 +8,64 @@ public class ParseCSVTest { - @Test - public void test1() throws FileNotFoundException { + @Test + public void test1() throws FileNotFoundException { - String csvFile = "test.csv"; + String csvFile = "test.csv"; - /** - * default java load file from /resources - * https://stackoverflow.com/questions/15749192/how-do-i-load-a-file-from-resource-folder - */ - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource(csvFile).getFile()); - //InputStream inputStream = new FileInputStream(file); + /** + * default java load file from /resources + * https://stackoverflow.com/questions/15749192/how-do-i-load-a-file-from-resource-folder + */ + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource(csvFile).getFile()); + // InputStream inputStream = new FileInputStream(file); - IFileUtils IFileUtils = new IFileUtils(); - List> data = IFileUtils.loadCSVFile(file); + IFileUtils IFileUtils = new IFileUtils(); + List> data = IFileUtils.loadCSVFile(file); - System.out.println(data.toArray().length); - data.stream().forEach(x -> System.out.println(x)); - } + System.out.println(data.toArray().length); + data.stream().forEach(x -> System.out.println(x)); + } - @Test - public void test2() throws FileNotFoundException { + @Test + public void test2() throws FileNotFoundException { - String csvFile = "test2.csv"; + String csvFile = "test2.csv"; - IFileUtils IFileUtils = new IFileUtils(); - List> data = IFileUtils.loadCSVFile(IFileUtils.getResourceDirFile(csvFile)); + IFileUtils IFileUtils = new IFileUtils(); + List> data = IFileUtils.loadCSVFile(IFileUtils.getResourceDirFile(csvFile)); - System.out.println(data.toArray().length); + System.out.println(data.toArray().length); - data.stream().skip(1).forEach(x -> System.out.println(x.toString().replace("\"", "0"))); + data.stream().skip(1).forEach(x -> System.out.println(x.toString().replace("\"", "0"))); - System.out.println("=============="); + System.out.println("=============="); - data.stream().skip(1).forEach(x -> { - String id = x.get(0).replace("\"", "0"); - String name = x.get(1).replace("\"", "0"); - String balance = x.get(2).replace("\"", "0"); + data.stream() + .skip(1) + .forEach( + x -> { + String id = x.get(0).replace("\"", "0"); + String name = x.get(1).replace("\"", "0"); + String balance = x.get(2).replace("\"", "0"); - System.out.println("id = " + id + " name = " + name + " balance = " + balance); - }); + System.out.println("id = " + id + " name = " + name + " balance = " + balance); + }); - System.out.println("=============="); + System.out.println("=============="); - // String x = r1.getId() == null ? "0.0" : r1.getId(); + // String x = r1.getId() == null ? "0.0" : r1.getId(); - data.stream().skip(1).forEach(x -> { - String id = x.get(0).equals("") ? "0" : x.get(0); - String name = x.get(1).length() < 1 ? "0" : x.get(1); // this one works - String balance = x.get(2) == "" ? "0" : x.get(2); - - System.out.println("id = " + id + " name = " + name + " balance = " + balance); - }); - - } + data.stream() + .skip(1) + .forEach( + x -> { + String id = x.get(0).equals("") ? "0" : x.get(0); + String name = x.get(1).length() < 1 ? "0" : x.get(1); // this one works + String balance = x.get(2) == "" ? "0" : x.get(2); + System.out.println("id = " + id + " name = " + name + " balance = " + balance); + }); + } } diff --git a/src/main/java/dev/StreamTest1.java b/src/main/java/dev/StreamTest1.java index 17cb6ab3..bf0d9066 100644 --- a/src/main/java/dev/StreamTest1.java +++ b/src/main/java/dev/StreamTest1.java @@ -1,10 +1,6 @@ package dev; -/** - * Ref : - * - https://github.com/yennanliu/til/blob/master/doc/pic/stream_map1.png - */ - +/** Ref : - https://github.com/yennanliu/til/blob/master/doc/pic/stream_map1.png */ import dev.bean.Car; import java.util.Arrays; import java.util.List; @@ -14,102 +10,99 @@ public class StreamTest1 { - /** - * - * Stream map return demo - */ - @Test - public void MapTest1(){ - - Car car1 = new Car(1,"TESLA",1000); - Car car2 = new Car(2,"BENZ",3000); - Car car3 = new Car(3,"LEXUS",2000); - - // https://stackoverflow.com/questions/2607289/converting-array-to-list-in-java - Car[] cars = new Car[]{car1, car2, car3}; - List car_list = Arrays.asList(cars); - - car_list.stream().forEach(x -> System.out.println(x)); - - System.out.println(""); - - List brand_list = car_list.stream().map(x -> { - String brand = x.getBrand(); - return brand; - }).collect(Collectors.toList()); - - System.out.println(brand_list); - } - - - /** - * GroupBy basic - * - * Map> monthReportMap = myReport.stream() - * .collect(Collectors.groupingBy(MyReport::getOwnerGroupKey)); - */ - @Test - public void GroupByTest1(){ - - Car car1 = new Car(1,"TESLA",1000); - Car car2 = new Car(2,"BENZ",3000); - Car car3 = new Car(3,"LEXUS",2000); - Car car4 = new Car(4,"LEXUS",1222); - Car car5 = new Car(5,"LEXUS",9000); - - // https://stackoverflow.com/questions/2607289/converting-array-to-list-in-java - Car[] cars = new Car[]{car1, car2, car3, car4, car5}; - List car_list = Arrays.asList(cars); - - Map> groupByResult = car_list - .stream() - .collect(Collectors.groupingBy(x -> x.getBrand()) - ); - - System.out.println(">>> groupByResult = " + groupByResult); // groupByResult = {BENZ=[Car{id=2, brand='BENZ', price=3000.0}], LEXUS=[Car{id=3, brand='LEXUS', price=2000.0}, Car{id=4, brand='LEXUS', price=1222.0}, Car{id=5, brand='LEXUS', price=9000.0}], TESLA=[Car{id=1, brand='TESLA', price=1000.0}]} - - System.out.println(); - - // https://stackoverflow.com/questions/49605558/is-it-possible-to-use-foreach-in-groupingby-in-java-stream - groupByResult.forEach((x,y) -> System.out.println("x = " + x + " y = " + y)); - } - - /** - * 1) groupingBy Car::getId - * 2) Collectors.groupingBy(Car::getIdAndBrand) : group by custom get method - */ - @Test - public void GroupByTest2(){ - - Car car1 = new Car(1,"TESLA",1000); - Car car2 = new Car(2,"BENZ",3000); - Car car3 = new Car(3,"LEXUS",2000); - Car car4 = new Car(4,"LEXUS",1222); - Car car5 = new Car(5,"LEXUS",9000); - Car car6 = new Car(1,"TESLA",1000); - - Car[] cars = new Car[]{car1, car2, car3, car4, car5, car6}; - List car_list = Arrays.asList(cars); - - Map> groupByResult = car_list - .stream() - .collect(Collectors.groupingBy(Car::getId) - ); - - System.out.println(">>> groupByResult = " + groupByResult); - - System.out.println(); - - // https://stackoverflow.com/questions/49605558/is-it-possible-to-use-foreach-in-groupingby-in-java-stream - groupByResult.forEach((x,y) -> System.out.println("x = " + x + " y = " + y)); - - - Map> groupByResult2 = car_list - .stream() - .collect(Collectors.groupingBy(Car::getIdAndBrand) - ); - - System.out.println(">>> groupByResult2 = " + groupByResult2); - } - + /** Stream map return demo */ + @Test + public void MapTest1() { + + Car car1 = new Car(1, "TESLA", 1000); + Car car2 = new Car(2, "BENZ", 3000); + Car car3 = new Car(3, "LEXUS", 2000); + + // https://stackoverflow.com/questions/2607289/converting-array-to-list-in-java + Car[] cars = new Car[] {car1, car2, car3}; + List car_list = Arrays.asList(cars); + + car_list.stream().forEach(x -> System.out.println(x)); + + System.out.println(); + + List brand_list = + car_list.stream() + .map( + x -> { + String brand = x.getBrand(); + return brand; + }) + .collect(Collectors.toList()); + + System.out.println(brand_list); + } + + /** + * GroupBy basic + * + *

Map> monthReportMap = myReport.stream() + * .collect(Collectors.groupingBy(MyReport::getOwnerGroupKey)); + */ + @Test + public void GroupByTest1() { + + Car car1 = new Car(1, "TESLA", 1000); + Car car2 = new Car(2, "BENZ", 3000); + Car car3 = new Car(3, "LEXUS", 2000); + Car car4 = new Car(4, "LEXUS", 1222); + Car car5 = new Car(5, "LEXUS", 9000); + + // https://stackoverflow.com/questions/2607289/converting-array-to-list-in-java + Car[] cars = new Car[] {car1, car2, car3, car4, car5}; + List car_list = Arrays.asList(cars); + + Map> groupByResult = + car_list.stream().collect(Collectors.groupingBy(x -> x.getBrand())); + + System.out.println( + ">>> groupByResult = " + + groupByResult); // groupByResult = {BENZ=[Car{id=2, brand='BENZ', price=3000.0}], + // LEXUS=[Car{id=3, brand='LEXUS', price=2000.0}, Car{id=4, + // brand='LEXUS', price=1222.0}, Car{id=5, brand='LEXUS', + // price=9000.0}], TESLA=[Car{id=1, brand='TESLA', price=1000.0}]} + + System.out.println(); + + // https://stackoverflow.com/questions/49605558/is-it-possible-to-use-foreach-in-groupingby-in-java-stream + groupByResult.forEach((x, y) -> System.out.println("x = " + x + " y = " + y)); + } + + /** + * 1) groupingBy Car::getId 2) Collectors.groupingBy(Car::getIdAndBrand) : group by custom get + * method + */ + @Test + public void GroupByTest2() { + + Car car1 = new Car(1, "TESLA", 1000); + Car car2 = new Car(2, "BENZ", 3000); + Car car3 = new Car(3, "LEXUS", 2000); + Car car4 = new Car(4, "LEXUS", 1222); + Car car5 = new Car(5, "LEXUS", 9000); + Car car6 = new Car(1, "TESLA", 1000); + + Car[] cars = new Car[] {car1, car2, car3, car4, car5, car6}; + List car_list = Arrays.asList(cars); + + Map> groupByResult = + car_list.stream().collect(Collectors.groupingBy(Car::getId)); + + System.out.println(">>> groupByResult = " + groupByResult); + + System.out.println(); + + // https://stackoverflow.com/questions/49605558/is-it-possible-to-use-foreach-in-groupingby-in-java-stream + groupByResult.forEach((x, y) -> System.out.println("x = " + x + " y = " + y)); + + Map> groupByResult2 = + car_list.stream().collect(Collectors.groupingBy(Car::getIdAndBrand)); + + System.out.println(">>> groupByResult2 = " + groupByResult2); + } } diff --git a/src/main/java/dev/StringTest.java b/src/main/java/dev/StringTest.java index f19d438f..128f1e9d 100644 --- a/src/main/java/dev/StringTest.java +++ b/src/main/java/dev/StringTest.java @@ -5,315 +5,309 @@ import org.junit.jupiter.api.Test; public class StringTest { - public static void main(String[] args) { + public static void main(String[] args) { + + String s3Link = "s3://my-bucket/my-task/yyyy/2022-08-04/zz/202208040145.zip"; + String[] l1 = s3Link.split("/"); + Arrays.stream(l1).forEach(x -> System.out.println(x)); + + System.out.println("=============="); + String[] l2 = s3Link.split("my-task"); + Arrays.stream(l2).forEach(x -> System.out.println(x)); + + System.out.println(">>> " + "/" + l1[2] + l2[1]); + + System.out.println("=============="); + + System.out.println(l1[2]); + + // https://stackoverflow.com/questions/39860739/how-to-get-first-and-last-element-in-an-array-in-java + // Array of doubles + double[] array_doubles = {2.5, 6.2, 8.2, 4846.354, 9.6}; + + // First position + double firstNum = array_doubles[0]; // 2.5 + } + + @Test + public void test2() { + + String s3Link = + "s3://xxx/data-download-task/zzz/2022-08-19/41a10b1e-1f5e-11ed-92e6-0617fbf35557/202208190128.zip"; + String s3CSVBucket = s3Link.split("/")[2]; + String s3CSVPath = "data-download-task" + s3Link.split("data-download-task")[1]; + + System.out.println(">>> s3Link = " + s3Link); + System.out.println(">>> s3CSVBucket = " + s3CSVBucket); + System.out.println(">>> s3CSVPath = " + s3CSVPath); + } + + @Test + public void test3() { + + String s3Link = ""; + String s3LinkCleaned = s3Link.split("\\\\?X-Amz")[0].replace("?", ""); + String s3CSVBucket = s3LinkCleaned.split("/")[2].replace(".s3.amazonaws.com", ""); + String s3CSVPath = "data-download-task" + s3LinkCleaned.split("data-download-task")[1]; + + System.out.println(">>> s3Link = " + s3Link); + System.out.println(">>> s3LinkCleaned = " + s3LinkCleaned); + System.out.println(">>> s3CSVBucket = " + s3CSVBucket); + System.out.println(">>> s3CSVPath = " + s3CSVPath); + } + + @Test + public void test4() { + + String param = ""; + System.out.println(param); + System.out.println(param.split("majorUserId")[0]); + System.out.println(param.split("majorUserId")[1]); + System.out.println( + param + .split("majorUserId")[1] + .split(",")[0] + .replace("[", "") + .replace("]", "") + .replaceAll("\"", "") + .replace(":", "")); + + System.out.println( + Long.parseLong( + param + .split("majorUserId")[1] + .split(",")[0] + .replace("[", "") + .replace("]", "") + .replaceAll("\"", "") + .replace(":", ""))); + } + + @Test + public void test5() { + + String id = "000"; + System.out.println(Long.parseLong(id)); + } + + @Test + public void test6() { + String[] data = new String[] {"a", "b", "c"}; + System.out.println(data); + Arrays.stream(data).forEach(x -> System.out.println(x)); + + System.out.println(); + + String[] data2 = new String[] {"a", "b", "c", "", "d", "e", "f", "g"}; + Arrays.stream(data2).filter(x -> x.length() > 0).forEach(x -> System.out.println(x)); + + String[] data3 = new String[] {"a", "b", "c", "", "d", null, "e", "f", "g", null}; + // TODO : do same on data3 + } + + @Test + public void test7() { + String snapShotUTC = null; + snapShotUTC.replace(" ", " 23:59:59 "); + } + + @Test + public void test8() { + String snapShotUTC = ""; + snapShotUTC.replace(" ", " 23:59:59 "); + } + + @Test + public void test9() { + String x = "Account s"; + String y = "v_account_s"; + + String x_1 = "v" + x.toLowerCase().replace(" ", "_"); + System.out.println("x_1 = " + x_1); + + System.out.println(y.contains(x_1.toLowerCase())); + } + + @Test + public void test10() { + String x = "xxxx"; + + String[] x_ = x.split("\\?"); + System.out.println(x_[0]); + System.out.println(x_[1]); + System.out.println(x_.length); + System.out.println(x.contains("?")); + + System.out.println(); + + String x2 = x.replaceAll("^[!@#?\\$%\\^\\&*\\)\\(+=._-]", ""); + System.out.println(x2); + + System.out.println(); + + String y = "wdvever"; + String[] y_ = y.split("\\?"); + System.out.println(y_[0]); + // System.out.println(y_[1]); + System.out.println(y.contains("?")); + } + + @Test + public void test11() { + + // https://www.delftstack.com/zh-tw/howto/java/how-to-print-a-float-with-2-decimal-places-in-java/ + + float Pi = 3.1415f; + System.out.println(Pi); + // Get only 2 decimal points + System.out.printf("%.2f", Pi); + + System.out.println("------------"); - String s3Link = "s3://my-bucket/my-task/yyyy/2022-08-04/zz/202208040145.zip"; - String[] l1 = s3Link.split("/"); - Arrays.stream(l1).forEach(x -> System.out.println(x)); - - System.out.println("=============="); - String[] l2 = s3Link.split("my-task"); - Arrays.stream(l2).forEach(x -> System.out.println(x)); - - System.out.println(">>> " + "/" + l1[2] + l2[1]); - - System.out.println("=============="); - - System.out.println(l1[2]); - - // https://stackoverflow.com/questions/39860739/how-to-get-first-and-last-element-in-an-array-in-java - // Array of doubles - double[] array_doubles = {2.5, 6.2, 8.2, 4846.354, 9.6}; - - // First position - double firstNum = array_doubles[0]; // 2.5 - } - - @Test - public void test2(){ - - String s3Link = "s3://xxx/data-download-task/zzz/2022-08-19/41a10b1e-1f5e-11ed-92e6-0617fbf35557/202208190128.zip"; - String s3CSVBucket = s3Link.split("/")[2]; - String s3CSVPath = "data-download-task" + s3Link.split("data-download-task")[1]; - - System.out.println(">>> s3Link = "+ s3Link); - System.out.println(">>> s3CSVBucket = "+ s3CSVBucket); - System.out.println(">>> s3CSVPath = "+ s3CSVPath); - - } - - @Test - public void test3(){ - - String s3Link = ""; - String s3LinkCleaned = s3Link.split("\\\\?X-Amz")[0].replace("?", ""); - String s3CSVBucket = s3LinkCleaned.split("/")[2].replace(".s3.amazonaws.com", ""); - String s3CSVPath = "data-download-task" + s3LinkCleaned.split("data-download-task")[1]; - - System.out.println(">>> s3Link = "+ s3Link); - System.out.println(">>> s3LinkCleaned = "+ s3LinkCleaned); - System.out.println(">>> s3CSVBucket = "+ s3CSVBucket); - System.out.println(">>> s3CSVPath = "+ s3CSVPath); - } + float Pi2 = 3.1415f; + System.out.println(Pi2); + // Get only 2 decimal points + String str = String.format("%.02f", Pi2); + Pi2 = Float.valueOf(str); + System.out.println(Pi2); + } - @Test - public void test4(){ + @Test + public void test12() { - String param = ""; - System.out.println(param); - System.out.println(param.split("majorUserId")[0]); - System.out.println(param.split("majorUserId")[1]); - System.out.println( - param.split("majorUserId")[1].split(",")[0] - .replace("[","") - .replace("]","") - .replaceAll("\"","") - .replace(":","") - ); + // https://www.delftstack.com/zh-tw/howto/java/how-to-round-a-double-to-two-decimal-places-in-java/ - System.out.println( - Long.parseLong( - param.split("majorUserId")[1].split(",")[0] - .replace("[","") - .replace("]","") - .replaceAll("\"","") - .replace(":","")) - ); + double val1 = 6482.236789; + System.out.println("Double value: " + val1); - } + DecimalFormat df = new DecimalFormat("###.##"); + System.out.println("Rounded Double value (DecimalFormat): " + df.format(val1)); - @Test - public void test5(){ + String val2 = df.format(val1); + System.out.println("val2 = " + val2); - String id = "000"; - System.out.println(Long.parseLong(id)); - } + String val1_ = "6482.236789"; + String val2_ = df.format(Double.parseDouble(val1_)); + System.out.println("val2_ = " + val2_); + } - @Test - public void test6(){ - String[] data = new String[]{"a","b","c"}; - System.out.println(data); - Arrays.stream(data).forEach(x -> System.out.println(x)); + @Test + public void test13() { - System.out.println(); + // String fileName = "xxx.pdf"; + String fileName = "xxx.csv"; + String fileNameUpdated = fileName.replace("pdf", "zip"); + System.out.println(fileNameUpdated); + } - String[] data2 = new String[]{"a","b","c","","d","e","f","g"}; - Arrays.stream(data2) - .filter( x -> x.length() > 0) - .forEach(x -> System.out.println(x)); + @Test + public void test14() { - String[] data3 = new String[]{"a","b","c","","d",null,"e","f","g", null}; - // TODO : do same on data3 - } + String x = "abc"; + String msg = + String.valueOf(new StringBuffer().append("123").append(" >>>>").append(" x = ").append(x)); - @Test - public void test7(){ - String snapShotUTC = null; - snapShotUTC.replace(" ", " 23:59:59 "); - } + System.out.println(">>> msg = " + msg); + } - @Test - public void test8(){ - String snapShotUTC = ""; - snapShotUTC.replace(" ", " 23:59:59 "); - } + @Test + public void test15() { - @Test - public void test9(){ - String x = "Account s"; - String y = "v_account_s"; + // https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html + // https://stackoverflow.com/questions/20774951/bigdecimal-string-formatting-with-thousands-separator + DecimalFormat formatter1 = new DecimalFormat("###,###"); - String x_1 = "v" + x.toLowerCase().replace(" ", "_"); - System.out.println("x_1 = " + x_1); + String num1 = "10000000"; + String num1_ = formatter1.format(Double.parseDouble(num1)); + System.out.println("num1_ = " + num1_); - System.out.println(y.contains(x_1.toLowerCase())); - } + String num2 = "100"; + String num2_ = formatter1.format(Double.parseDouble(num2)); + System.out.println("num2_ = " + num2_); - @Test - public void test10(){ - String x = "xxxx"; + // String num3 = null; + // String num3_ = formatter1.format(Double.parseDouble(num3)); + // System.out.println("num3_ = " + num3_); - String[] x_ = x.split("\\?"); - System.out.println(x_[0]); - System.out.println(x_[1]); - System.out.println(x_.length); - System.out.println(x.contains("?")); + String num4 = "10000000.001"; + String num4_ = formatter1.format(Double.parseDouble(num4)); + System.out.println("num4_ = " + num4_); - System.out.println(); + DecimalFormat formatter2 = new DecimalFormat("###,###.###"); - String x2 = x.replaceAll("^[!@#?\\$%\\^\\&*\\)\\(+=._-]", ""); - System.out.println(x2); + String num4_2 = formatter2.format(Double.parseDouble(num4)); + System.out.println("num4_2 = " + num4_2); - System.out.println(); + String num5 = "0.001"; + String num5_2 = formatter2.format(Double.parseDouble(num5)); + System.out.println("num5_2 = " + num5_2); - String y = "wdvever"; - String[] y_ = y.split("\\?"); - System.out.println(y_[0]); -// System.out.println(y_[1]); - System.out.println(y.contains("?")); - } + String num6 = "10000"; + String num6_2 = formatter2.format(Double.parseDouble(num6)); + System.out.println("num6_2 = " + num6_2); + } - @Test - public void test11(){ + @Test + public void test16() { + Object x = null; + // System.out.println(x.toString()); + System.out.println(x); - // https://www.delftstack.com/zh-tw/howto/java/how-to-print-a-float-with-2-decimal-places-in-java/ + Object y = "123"; + System.out.println(y); + } - float Pi = 3.1415f; - System.out.println(Pi); - // Get only 2 decimal points - System.out.printf("%.2f", Pi); + @Test + public void test17() { - System.out.println("------------"); + String url = "xxx"; + System.out.println(url); - float Pi2 = 3.1415f; - System.out.println(Pi2); - // Get only 2 decimal points - String str = String.format("%.02f", Pi2); - Pi2 = Float.valueOf(str); - System.out.println(Pi2); - } + String[] x = url.split("\\\\?X-Amz"); + System.out.println(x.toString()); + System.out.println(); + // Arrays.stream(x).forEach(y -> System.out.println(y)); - @Test - public void test12(){ + String cleanedURL = x[0].replace("?", ""); + System.out.println(cleanedURL); - // https://www.delftstack.com/zh-tw/howto/java/how-to-round-a-double-to-two-decimal-places-in-java/ + System.out.println(); + String[] y = cleanedURL.split("/"); + Arrays.stream(y).forEach(k -> System.out.println(k)); - double val1 = 6482.236789; - System.out.println("Double value: "+val1); + System.out.println("--> bucket = " + y[3]); + System.out.println("--> bucket = " + cleanedURL.replace("//", "/").split("/")[2]); - DecimalFormat df = new DecimalFormat("###.##"); - System.out.println("Rounded Double value (DecimalFormat): "+ df.format(val1)); + // List key = Arrays.stream(cleanedURL + // .replace("//", "/") + // .split("/")).collect(Collectors.toList()); - String val2 = df.format(val1); - System.out.println("val2 = " + val2); + String text = + "\"OR\\n\\nThe Central Site Engineering\\u2019s \\u201cfrontend\\u201d, where developers turn to\""; + // text = text.replaceAll("(\\\\n)+"," ") + // .replaceAll("\\\\u[0-9A-Ha-h]{4}", ""); + // + // System.out.println(text); - String val1_ = "6482.236789"; - String val2_ = df.format(Double.parseDouble(val1_)); - System.out.println("val2_ = " + val2_); - } - - @Test - public void test13(){ - - //String fileName = "xxx.pdf"; - String fileName = "xxx.csv"; - String fileNameUpdated = fileName.replace("pdf", "zip"); - System.out.println(fileNameUpdated); - } - - @Test - public void test14(){ - - String x = "abc"; - String msg = String.valueOf( - new StringBuffer().append("123").append(" >>>>").append(" x = ").append(x)); - - System.out.println(">>> msg = " + msg); - } - - @Test - public void test15(){ - - // https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html - // https://stackoverflow.com/questions/20774951/bigdecimal-string-formatting-with-thousands-separator - DecimalFormat formatter1 = new DecimalFormat("###,###"); - - String num1 = "10000000"; - String num1_ = formatter1.format(Double.parseDouble(num1)); - System.out.println("num1_ = " + num1_); - - String num2 = "100"; - String num2_ = formatter1.format(Double.parseDouble(num2)); - System.out.println("num2_ = " + num2_); - -// String num3 = null; -// String num3_ = formatter1.format(Double.parseDouble(num3)); -// System.out.println("num3_ = " + num3_); - - String num4 = "10000000.001"; - String num4_ = formatter1.format(Double.parseDouble(num4)); - System.out.println("num4_ = " + num4_); - - DecimalFormat formatter2 = new DecimalFormat("###,###.###"); - - String num4_2 = formatter2.format(Double.parseDouble(num4)); - System.out.println("num4_2 = " + num4_2); - - String num5 = "0.001"; - String num5_2 = formatter2.format(Double.parseDouble(num5)); - System.out.println("num5_2 = " + num5_2); - - - String num6 = "10000"; - String num6_2 = formatter2.format(Double.parseDouble(num6)); - System.out.println("num6_2 = " + num6_2); - } - - @Test - public void test16(){ - Object x = null; - //System.out.println(x.toString()); - System.out.println(x); - - Object y = "123"; - System.out.println(y.toString()); - } - - @Test - public void test17(){ - - String url = "xxx"; - - System.out.println(url); - - String[] x = url.split("\\\\?X-Amz"); - System.out.println(x.toString()); - System.out.println(); - //Arrays.stream(x).forEach(y -> System.out.println(y)); - - String cleanedURL = x[0].replace("?", ""); - System.out.println(cleanedURL); - - System.out.println(); - String[] y = cleanedURL.split("/"); - Arrays.stream(y).forEach(k -> System.out.println(k)); - - System.out.println("--> bucket = " + y[3]); - System.out.println("--> bucket = " + cleanedURL.replace("//", "/").split("/")[2]); - -// List key = Arrays.stream(cleanedURL -// .replace("//", "/") -// .split("/")).collect(Collectors.toList()); - - - String text = "\"OR\\n\\nThe Central Site Engineering\\u2019s \\u201cfrontend\\u201d, where developers turn to\""; - -// text = text.replaceAll("(\\\\n)+"," ") -// .replaceAll("\\\\u[0-9A-Ha-h]{4}", ""); -// -// System.out.println(text); - - String url_x = url - .replaceAll("\\b.*?amazonaws.com.*?\\b", "") + String url_x = + url.replaceAll("\\b.*?amazonaws.com.*?\\b", "") .split("X-Amz-Algorithm")[0] .replace("?", ""); - System.out.println("url_x = " + url_x); - - String url_y = url - .split("pdf-download-task")[1].split("X-Amz-Algorithm")[0].replace("?", ""); + System.out.println("url_x = " + url_x); - System.out.println("url_y = " + url_y); - } + String url_y = url.split("pdf-download-task")[1].split("X-Amz-Algorithm")[0].replace("?", ""); - @Test - public void test18(){ - String mystr = "xxx-portal-ttt.s3.ap-northeast-1.amazonaws.com"; - String[] x = mystr.split("\\."); - System.out.println(x.length); - System.out.println(x[0]); - } + System.out.println("url_y = " + url_y); + } + @Test + public void test18() { + String mystr = "xxx-portal-ttt.s3.ap-northeast-1.amazonaws.com"; + String[] x = mystr.split("\\."); + System.out.println(x.length); + System.out.println(x[0]); + } } diff --git a/src/main/java/dev/TimeStampTest.java b/src/main/java/dev/TimeStampTest.java index 8c649758..25456740 100644 --- a/src/main/java/dev/TimeStampTest.java +++ b/src/main/java/dev/TimeStampTest.java @@ -1,9 +1,8 @@ package dev; -import org.junit.jupiter.api.Test; - import java.text.SimpleDateFormat; import java.util.Date; +import org.junit.jupiter.api.Test; public class TimeStampTest { diff --git a/src/main/java/dev/bean/BigDecimalTest.java b/src/main/java/dev/bean/BigDecimalTest.java index 24aab470..b47aa9e7 100644 --- a/src/main/java/dev/bean/BigDecimalTest.java +++ b/src/main/java/dev/bean/BigDecimalTest.java @@ -5,18 +5,17 @@ public class BigDecimalTest { - @Test - public void test1(){ + @Test + public void test1() { - // https://stackoverflow.com/questions/60810045/convert-string-to-double-without-scientific-notation + // https://stackoverflow.com/questions/60810045/convert-string-to-double-without-scientific-notation - String yourString = "7.234348087737378E8"; - BigDecimal value = new BigDecimal(yourString); - double doubleValue = value.doubleValue(); - - System.out.println(value); - System.out.println(value.toString()); - System.out.println(doubleValue); - } + String yourString = "7.234348087737378E8"; + BigDecimal value = new BigDecimal(yourString); + double doubleValue = value.doubleValue(); + System.out.println(value); + System.out.println(value); + System.out.println(doubleValue); + } } diff --git a/src/main/java/dev/bean/Data.java b/src/main/java/dev/bean/Data.java index 55493368..264bd0e2 100644 --- a/src/main/java/dev/bean/Data.java +++ b/src/main/java/dev/bean/Data.java @@ -6,72 +6,71 @@ public class Data implements Comparable { - private String id; - private String createTime; - private String[] dataPoints; - - public Data(String id, String createTime, String[] dataPoints) { - this.id = id; - this.createTime = createTime; - this.dataPoints = dataPoints; - } - - public Data() { - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getCreateTime() { - return createTime; - } - - public void setCreateTime(String createTime) { - this.createTime = createTime; + private String id; + private String createTime; + private String[] dataPoints; + + public Data(String id, String createTime, String[] dataPoints) { + this.id = id; + this.createTime = createTime; + this.dataPoints = dataPoints; + } + + public Data() {} + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getCreateTime() { + return createTime; + } + + public void setCreateTime(String createTime) { + this.createTime = createTime; + } + + public String[] getDataPoints() { + return dataPoints; + } + + public void setDataPoints(String[] dataPoints) { + this.dataPoints = dataPoints; + } + + @Override + public String toString() { + return "Data{" + + "id='" + + id + + '\'' + + ", createTime='" + + createTime + + '\'' + + ", dataPoints=" + + Arrays.toString(dataPoints) + + '}'; + } + + @Override + public int compareTo(Object o) { + if (o instanceof Data) { + Data data = (Data) o; + // + if (data.createTime.equals("others")) { + return -1; + } else if (Integer.valueOf(this.id) > Integer.valueOf(data.id)) { + return 1; + } else if (Integer.valueOf(this.id) < Integer.valueOf(data.id)) { + return -1; + } else { + return 0; + } } - - public String[] getDataPoints() { - return dataPoints; - } - - public void setDataPoints(String[] dataPoints) { - this.dataPoints = dataPoints; - } - - @Override - public String toString() { - return "Data{" + - "id='" + id + '\'' + - ", createTime='" + createTime + '\'' + - ", dataPoints=" + Arrays.toString(dataPoints) + - '}'; - } - - - @Override - public int compareTo(Object o) { - if (o instanceof Data){ - Data data = (Data) o; -// - if (data.createTime.equals("others")){ - return -1; - } - else if (Integer.valueOf(this.id) > Integer.valueOf(data.id)){ - return 1; - } - else if (Integer.valueOf(this.id) < Integer.valueOf(data.id)){ - return -1; - } - else{ - return 0; - } - } - throw new RuntimeException("input (price) type mismatch!"); - } - + throw new RuntimeException("input (price) type mismatch!"); + } } diff --git a/src/main/java/threadDev/Fibonacci.java b/src/main/java/threadDev/Fibonacci.java index a4e801eb..d92bb09c 100644 --- a/src/main/java/threadDev/Fibonacci.java +++ b/src/main/java/threadDev/Fibonacci.java @@ -1,27 +1,25 @@ package threadDev; - import java.io.Serializable; import java.util.concurrent.Callable; public class Fibonacci implements Callable, Serializable { - int input = 0; + int input = 0; - public Fibonacci() { - } + public Fibonacci() {} - public Fibonacci(int input) { - System.out.println("Fibonacci init ..., input = " + input); - this.input = input; - } + public Fibonacci(int input) { + System.out.println("Fibonacci init ..., input = " + input); + this.input = input; + } - public java.lang.Long call() { - return calculate (input); - } + public java.lang.Long call() { + return calculate(input); + } - private long calculate (int n) { - if (Thread.currentThread().isInterrupted()) return 0; - if (n <= 1) return n; - else return calculate(n-1) + calculate(n-2); - } + private long calculate(int n) { + if (Thread.currentThread().isInterrupted()) return 0; + if (n <= 1) return n; + else return calculate(n - 1) + calculate(n - 2); + } } diff --git a/src/main/java/threadDev/Test1.java b/src/main/java/threadDev/Test1.java index 23e32c2c..1e528d7e 100644 --- a/src/main/java/threadDev/Test1.java +++ b/src/main/java/threadDev/Test1.java @@ -3,68 +3,79 @@ import java.util.concurrent.*; public class Test1 { - public static void main(String[] args) { - final int CORE_POOL_SIZE = 10; - final int MAX_POOL_SIZE = 11; - final int KEEP_ALIVE_TIME = 60; + public static void main(String[] args) { + final int CORE_POOL_SIZE = 10; + final int MAX_POOL_SIZE = 11; + final int KEEP_ALIVE_TIME = 60; - ThreadPoolExecutor executor = new ThreadPoolExecutor( - CORE_POOL_SIZE, - MAX_POOL_SIZE, - KEEP_ALIVE_TIME, - TimeUnit.SECONDS, - new SynchronousQueue<>(), - new ThreadPoolExecutor.AbortPolicy() - ); + ThreadPoolExecutor executor = + new ThreadPoolExecutor( + CORE_POOL_SIZE, + MAX_POOL_SIZE, + KEEP_ALIVE_TIME, + TimeUnit.SECONDS, + new SynchronousQueue<>(), + new ThreadPoolExecutor.AbortPolicy()); - int N = 10; - Future future = executor.submit(() -> { - System.out.println("--> Thread name : " + Thread.currentThread().getName() + ", id = " + Thread.currentThread().getId()); - return new Fibonacci2(N).calculate(); - }); - - for (int i = 0; i < 3; i++) { - executor.submit(() -> { - System.out.println("--> Thread name : " + Thread.currentThread().getName() + ", id = " + Thread.currentThread().getId()); - new Fibonacci2(2).calculate(); + int N = 10; + Future future = + executor.submit( + () -> { + System.out.println( + "--> Thread name : " + + Thread.currentThread().getName() + + ", id = " + + Thread.currentThread().getId()); + return new Fibonacci2(N).calculate(); }); - } - try { - System.out.println("Waiting for future result..."); - Integer result = future.get(10, TimeUnit.SECONDS); - System.out.println("Future result: " + result); - } catch (TimeoutException e) { - System.out.println("Future task timed out, cancelling..."); - future.cancel(true); - } catch (ExecutionException e) { - System.out.println("Exception occurred during task execution"); - e.printStackTrace(); - } catch (InterruptedException e) { - System.out.println("Main thread interrupted"); - e.printStackTrace(); - } finally { - executor.shutdown(); - } + for (int i = 0; i < 3; i++) { + executor.submit( + () -> { + System.out.println( + "--> Thread name : " + + Thread.currentThread().getName() + + ", id = " + + Thread.currentThread().getId()); + new Fibonacci2(2).calculate(); + }); + } - System.out.println("Main method finished"); + try { + System.out.println("Waiting for future result..."); + Integer result = future.get(10, TimeUnit.SECONDS); + System.out.println("Future result: " + result); + } catch (TimeoutException e) { + System.out.println("Future task timed out, cancelling..."); + future.cancel(true); + } catch (ExecutionException e) { + System.out.println("Exception occurred during task execution"); + e.printStackTrace(); + } catch (InterruptedException e) { + System.out.println("Main thread interrupted"); + e.printStackTrace(); + } finally { + executor.shutdown(); } + + System.out.println("Main method finished"); + } } class Fibonacci2 { - private final int N; + private final int N; - public Fibonacci2(int N) { - this.N = N; - } + public Fibonacci2(int N) { + this.N = N; + } - public int calculate() { - System.out.println("Fibonacci2 calculate, N = " + N); - return fibonacci(N); - } + public int calculate() { + System.out.println("Fibonacci2 calculate, N = " + N); + return fibonacci(N); + } - private int fibonacci(int n) { - if (n <= 1) return n; - return fibonacci(n - 1) + fibonacci(n - 2); - } -} \ No newline at end of file + private int fibonacci(int n) { + if (n <= 1) return n; + return fibonacci(n - 1) + fibonacci(n - 2); + } +} diff --git a/src/main/java/threadDev/Test2.java b/src/main/java/threadDev/Test2.java new file mode 100644 index 00000000..4c0a2daa --- /dev/null +++ b/src/main/java/threadDev/Test2.java @@ -0,0 +1,37 @@ +package threadDev; + +// https://stackoverflow.com/questions/28043225/future-cancel-does-not-work + +import java.util.concurrent.*; + +public class Test2 { + public static void main(String[] args) { + + Runnable r = + new Runnable() { + @Override + public void run() { + try { + for (; ; ) {} + + } finally { + System.out.println("FINALLY"); + } + } + }; + + ExecutorService executor = Executors.newSingleThreadExecutor(); + + Future future = executor.submit(r); + try { + future.get(3, TimeUnit.SECONDS); + } catch (TimeoutException e) { + boolean c = future.cancel(true); + System.out.println("Timeout " + c); + } catch (InterruptedException | ExecutionException e) { + System.out.println("interrupted"); + } + System.out.println("END"); + } + +} diff --git a/src/main/java/utils/ParseValue.java b/src/main/java/utils/ParseValue.java index 2fbb62d2..7477fe9b 100644 --- a/src/main/java/utils/ParseValue.java +++ b/src/main/java/utils/ParseValue.java @@ -1,16 +1,15 @@ package utils; - public class ParseValue { - public boolean CheckPostive(Integer x) { - return x > 0; - } + public boolean CheckPostive(Integer x) { + return x > 0; + } - public int plus100(Integer x){ - return x + 100; - } + public int plus100(Integer x) { + return x + 100; + } - public Double GetSin(Integer x){ - return Math.sin(x); - } + public Double GetSin(Integer x) { + return Math.sin(x); + } }