From bcf7f45473946a0f84cb5600acd74a2e3cc4b2b5 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Sun, 25 Jun 2017 00:41:44 +0800 Subject: [PATCH 01/41] branch tutorial --- .gitignore | 23 +++++++++++++++++++++++ tutorial/HelloWorld.java | 6 ++++++ 2 files changed, 29 insertions(+) create mode 100644 tutorial/HelloWorld.java diff --git a/.gitignore b/.gitignore index 37c071e..57a89ad 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,26 @@ .idea/**/* interfacetest.iml /test-output/ +### Java template +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +#*.jar +*.war +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* diff --git a/tutorial/HelloWorld.java b/tutorial/HelloWorld.java new file mode 100644 index 0000000..933c507 --- /dev/null +++ b/tutorial/HelloWorld.java @@ -0,0 +1,6 @@ +public class HelloWorld { + public static void main(String []args){ + System.out.println("Hello World."); + } + +} \ No newline at end of file From e94117c2b41498a653cb78086f04fcc20a3866f6 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Sun, 25 Jun 2017 17:23:50 +0800 Subject: [PATCH 02/41] init tutorial --- src/tutorial/Employee.java | 33 +++++++ src/tutorial/EmployeeTest.java | 20 ++++ src/tutorial/HelloWorld.java | 32 +++++++ src/tutorial/ModifierTest.java | 35 +++++++ src/tutorial/Operators.java | 136 ++++++++++++++++++++++++++++ src/tutorial/PrimitiveTypeTest.java | 61 +++++++++++++ src/tutorial/Puppy.java | 27 ++++++ src/tutorial/StaticTest.java | 64 +++++++++++++ tutorial/HelloWorld.java | 6 -- 9 files changed, 408 insertions(+), 6 deletions(-) create mode 100644 src/tutorial/Employee.java create mode 100644 src/tutorial/EmployeeTest.java create mode 100644 src/tutorial/HelloWorld.java create mode 100644 src/tutorial/ModifierTest.java create mode 100644 src/tutorial/Operators.java create mode 100644 src/tutorial/PrimitiveTypeTest.java create mode 100644 src/tutorial/Puppy.java create mode 100644 src/tutorial/StaticTest.java delete mode 100644 tutorial/HelloWorld.java diff --git a/src/tutorial/Employee.java b/src/tutorial/Employee.java new file mode 100644 index 0000000..71e6b08 --- /dev/null +++ b/src/tutorial/Employee.java @@ -0,0 +1,33 @@ +/** + * Created by Oliver on 25/06/2017. + */ +public class Employee { + int age; + double salary; + String name; + String designation; + + public Employee(String name) { + this.name = name; + } + + public void setAge(int age) { + this.age = age; + } + + public void setSalary(double salary) { + this.salary = salary; + } + + public void setDesignation(String designation) { + this.designation = designation; + } + + public void printEmployee() { + System.out.println("Employee name: " + this.name); + System.out.println("Employee age: " + this.age); + System.out.println("Employee designation: " + this.designation); + System.out.println("Employee salary: " + this.salary); + } + +} diff --git a/src/tutorial/EmployeeTest.java b/src/tutorial/EmployeeTest.java new file mode 100644 index 0000000..290cec9 --- /dev/null +++ b/src/tutorial/EmployeeTest.java @@ -0,0 +1,20 @@ +/** + * Created by Oliver on 25/06/2017. + */ +public class EmployeeTest { + public static void main(String []args) { + // java因强制要求类名(唯一的public类)和文件名统一,因此在引用其它类时无需显式声明。在编译时,编译器会根据类名去寻找同名文件。 + Employee A = new Employee("Thomas"); + Employee B = new Employee("Jane"); + + A.age = 30; + A.designation = "Programmer"; + A.salary = 30000; + A.printEmployee(); + + B.age = 28; + B.designation = "HR"; + B.salary = 20000; + B.printEmployee(); + } +} diff --git a/src/tutorial/HelloWorld.java b/src/tutorial/HelloWorld.java new file mode 100644 index 0000000..4337809 --- /dev/null +++ b/src/tutorial/HelloWorld.java @@ -0,0 +1,32 @@ +/** + * Created by Oliver on 25/06/2017. + */ +public class HelloWorld { + /* 这是第一个Java程序 + 它将打印Hello World + 这是一个多行注释的示例 + */ + public static void main(String[] args) { + + System.out.println("Hello World."); + FreshJuice juice = new FreshJuice("OrangeJuice"); + juice.size = FreshJuice.FreshJuiceSize.MEDIUM; + + } + +} + +class FreshJuice { + // 注意:枚举可以单独声明或者声明在类里面。方法、变量、构造函数也可以在枚举中定义 + enum FreshJuiceSize { + SMALL, MEDIUM, LARGE + } + + FreshJuiceSize size; + + // 显式地为类定义构造方法 + public FreshJuice(String name) { + System.out.println("The juice name is: " + name); + } +} + diff --git a/src/tutorial/ModifierTest.java b/src/tutorial/ModifierTest.java new file mode 100644 index 0000000..54359af --- /dev/null +++ b/src/tutorial/ModifierTest.java @@ -0,0 +1,35 @@ +/** + * Created by Oliver on 25/06/2017. + */ +public class ModifierTest { + /* + 默认的,也称为 default,在同一包内可见,不使用任何修饰符。 + 私有的,以 private 修饰符指定,在同一类内可见。 + 共有的,以 public 修饰符指定,对所有类可见。 + 受保护的,以 protected 修饰符指定,对同一包内的类和所有子类可见。 + */ + private static int numInstance = 0; + + protected static int getCount() { + return numInstance; + } + + protected static void addInstance() { + numInstance++; + } + + public ModifierTest() { + ModifierTest.addInstance(); + } + + public static void main(String[] args) { + System.out.println("Starting with: " + ModifierTest.getCount()); + for (int i = 0; i < 10; ++i) { + ModifierTest test = new ModifierTest(); + + } + System.out.println("Created: " + numInstance + " instances"); + + } + +} diff --git a/src/tutorial/Operators.java b/src/tutorial/Operators.java new file mode 100644 index 0000000..a87fc21 --- /dev/null +++ b/src/tutorial/Operators.java @@ -0,0 +1,136 @@ +/** + * Created by Oliver on 25/06/2017. + */ +public class Operators { + + public static void test_math() { + int a = 10; + int b = 20; + int c = 25; + int d = 25; + System.out.println("*****算术运算*****"); + System.out.println("10 + 20 = " + (a + b)); + System.out.println("10 - 20 = " + (a - b)); + System.out.println("10 * 20 = " + (a * b)); + System.out.println("20 / 10 = " + (b / a)); + System.out.println("20 % 10 = " + (b % a)); + System.out.println("25 % 10 = " + (c % a)); + System.out.println("10++ = " + (a++)); + System.out.println("10-- = " + (a--)); + // 查看 d++ 与 ++d 的不同 + System.out.println("25++ = " + (d++)); + System.out.println("++25 = " + (++d)); + } + + public static void test_relation() { + int a = 10; + int b = 20; + System.out.println("*****关系运算*****"); + System.out.println("10 == 20 = " + (a == b)); + System.out.println("10 != 20 = " + (a != b)); + System.out.println("10 > 20 = " + (a > b)); + System.out.println("10 < 20 = " + (a < b)); + System.out.println("20 >= 10 = " + (b >= a)); + System.out.println("20 <= 10 = " + (b <= a)); + } + + public static void test_bitwise() { + System.out.println("*****位运算*****"); + int a = 60; /* 60 = 0011 1100 */ + int b = 13; /* 13 = 0000 1101 */ + int c; + c = a & b; /* 12 = 0000 1100 */ + System.out.println("60 & 13 = " + c); + + c = a | b; /* 61 = 0011 1101 */ + System.out.println("60 | 13 = " + c); + + c = a ^ b; /* 49 = 0011 0001 */ + System.out.println("60 ^ 13 = " + c); + + c = ~a; /*-61 = 1100 0011 */ + System.out.println("~60 = " + c); + + c = a << 2; /* 240 = 1111 0000 */ + System.out.println("a << 2 = " + c); + + c = a >> 2; /* 15 = 1111 */ + System.out.println("a >> 2 = " + c); + + c = a >>> 2; /* 15 = 0000 1111 */ + System.out.println("a >>> 2 = " + c); + } + + public static void test_logic() { + System.out.println("*****逻辑运算*****"); + boolean a = true; + boolean b = false; + System.out.println("true && false: " + (a && b)); + System.out.println("true || false: " + (a || b)); + System.out.println("!(true && false): " + !(a && b)); + } + + public static void test_assign() { + System.out.println("*****赋值运算*****"); + int a = 10; + int b = 20; + int c = 0; + c = a + b; + System.out.println("c = a + b = " + c); + c += a; + System.out.println("c += a = " + c); + c -= a; + System.out.println("c -= a = " + c); + c *= a; + System.out.println("c *= a = " + c); + a = 10; + c = 15; + c /= a; + System.out.println("c /= a = " + c); + a = 10; + c = 15; + c %= a; + System.out.println("c %= a = " + c); + // 左移位赋值运算符, 相当与乘以2的2次方 + c <<= 2; + System.out.println("c <<= 2 = " + c); + // 右移位赋值运算符, 相当与除以2的2次方 + c >>= 2; + System.out.println("c >>= 2 = " + c); + c >>= 2; + System.out.println("c >>= a = " + c); + c &= a; + System.out.println("c &= 2 = " + c); + c ^= a; + System.out.println("c ^= a = " + c); + c |= a; + System.out.println("c |= a = " + c); + } + + public static void test_condition() { + System.out.println("*****条件运算*****"); + int a = 10; + int b = 0; + b = (a >= 10) ? 20 : 10; + System.out.println(b); + } + + public static void test_instanceof() { + /* 该运算符用于操作对象实例,检查该对象是否是一个特定类型(类类型或接口类型)*/ + System.out.println("*****instanceof运算*****"); + String name = "James"; + System.out.println(name instanceof String); + } + + public static void main(String args[]) { + test_math(); + test_relation(); + test_bitwise(); + test_logic(); + test_assign(); + test_condition(); + test_instanceof(); + } +} + + diff --git a/src/tutorial/PrimitiveTypeTest.java b/src/tutorial/PrimitiveTypeTest.java new file mode 100644 index 0000000..f3eb882 --- /dev/null +++ b/src/tutorial/PrimitiveTypeTest.java @@ -0,0 +1,61 @@ +/** + * Created by Oliver on 25/06/2017. + */ +public class PrimitiveTypeTest { + /* + 数值类型的基本类型的取值范围, 都已经以常量的形式定义在对应的包装类中了 + */ + public static void main(String[] args) { + // byte + System.out.println("基本类型:byte 二进制位数:" + Byte.SIZE); + System.out.println("包装类:java.lang.Byte"); + System.out.println("最小值:Byte.MIN_VALUE=" + Byte.MIN_VALUE); + System.out.println("最大值:Byte.MAX_VALUE=" + Byte.MAX_VALUE); + System.out.println(); + + // short + System.out.println("基本类型:short 二进制位数:" + Short.SIZE); + System.out.println("包装类:java.lang.Short"); + System.out.println("最小值:Short.MIN_VALUE=" + Short.MIN_VALUE); + System.out.println("最大值:Short.MAX_VALUE=" + Short.MAX_VALUE); + System.out.println(); + + // int + System.out.println("基本类型:int 二进制位数:" + Integer.SIZE); + System.out.println("包装类:java.lang.Integer"); + System.out.println("最小值:Integer.MIN_VALUE=" + Integer.MIN_VALUE); + System.out.println("最大值:Integer.MAX_VALUE=" + Integer.MAX_VALUE); + System.out.println(); + + // long + System.out.println("基本类型:long 二进制位数:" + Long.SIZE); + System.out.println("包装类:java.lang.Long"); + System.out.println("最小值:Long.MIN_VALUE=" + Long.MIN_VALUE); + System.out.println("最大值:Long.MAX_VALUE=" + Long.MAX_VALUE); + System.out.println(); + + // float + System.out.println("基本类型:float 二进制位数:" + Float.SIZE); + System.out.println("包装类:java.lang.Float"); + System.out.println("最小值:Float.MIN_VALUE=" + Float.MIN_VALUE); + System.out.println("最大值:Float.MAX_VALUE=" + Float.MAX_VALUE); + System.out.println(); + + // double + System.out.println("基本类型:double 二进制位数:" + Double.SIZE); + System.out.println("包装类:java.lang.Double"); + System.out.println("最小值:Double.MIN_VALUE=" + Double.MIN_VALUE); + System.out.println("最大值:Double.MAX_VALUE=" + Double.MAX_VALUE); + System.out.println(); + + // char + System.out.println("基本类型:char 二进制位数:" + Character.SIZE); + System.out.println("包装类:java.lang.Character"); + // 以数值形式而不是字符形式将Character.MIN_VALUE输出到控制台 + System.out.println("最小值:Character.MIN_VALUE=" + + (int) Character.MIN_VALUE); + // 以数值形式而不是字符形式将Character.MAX_VALUE输出到控制台 + System.out.println("最大值:Character.MAX_VALUE=" + + (int) Character.MAX_VALUE); + } +} \ No newline at end of file diff --git a/src/tutorial/Puppy.java b/src/tutorial/Puppy.java new file mode 100644 index 0000000..a1e2d69 --- /dev/null +++ b/src/tutorial/Puppy.java @@ -0,0 +1,27 @@ +/** + * Created by Oliver on 25/06/2017. + */ +public class Puppy { + int age; + + public Puppy(String name) { + System.out.println("My name is " + name); + } + + public int getAge() { + System.out.println("Puppy is " + age + " years old."); + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public static void main(String []args) { + Puppy puppy = new Puppy("Tommy"); + puppy.setAge(5); + puppy.getAge(); + puppy.age = 10; + System.out.println("Puppy is " + puppy.age + " years old."); + } +} diff --git a/src/tutorial/StaticTest.java b/src/tutorial/StaticTest.java new file mode 100644 index 0000000..ef9eab8 --- /dev/null +++ b/src/tutorial/StaticTest.java @@ -0,0 +1,64 @@ +/** + * Created by Oliver on 25/06/2017. + */ +public class StaticTest { + // 类变量赋值: 无final修饰,声明时赋值,构造器中赋值,静态语句块或静态方法赋值 + private static int staticInt = 2; + private int random = 2; + + public StaticTest() { + staticInt++; + random++; + } + + public static void main(String[] args) { + System.out.println("类变量与对象变量的值变化"); + StaticTest test = new StaticTest(); + System.out.println(" 实例1:staticInt:" + test.staticInt + "----random:" + test.random); + StaticTest test2 = new StaticTest(); + System.out.println(" 实例2:staticInt:" + test2.staticInt + "----random:" + test.random); + + System.out.println("静态变量赋值"); + System.out.println(" 静态语句块起作用:" + A.staticA); + A a = new A(); + System.out.println(" 构造器起作用:" + a.staticA); + a.toChange(); + System.out.println(" 静态方法1起作用:" + A.staticA); + a.toChange2(); + System.out.println(" 静态方法2起作用:" + A.staticA); + + System.out.println("常量赋值"); + System.out.println(" 静态语句赋值:" + B.staticB); + } +} + +class A { + public static String staticA = "A"; + + //静态语句块修改值 + static { + staticA = "A1"; + } + + //构造器修改值 + public A() { + staticA = "A2"; + } + //静态方法起作用 + + public static void toChange() { + staticA = "A3"; + } + + public static void toChange2() { + staticA = "A4"; + } +} + +class B { + public static final String staticB; // 声明与赋值分离 + + static { + staticB = "B"; + } +} diff --git a/tutorial/HelloWorld.java b/tutorial/HelloWorld.java deleted file mode 100644 index 933c507..0000000 --- a/tutorial/HelloWorld.java +++ /dev/null @@ -1,6 +0,0 @@ -public class HelloWorld { - public static void main(String []args){ - System.out.println("Hello World."); - } - -} \ No newline at end of file From 5a1487a3eff2f67cd3fb183e6e049acb1dfc2120 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Sun, 25 Jun 2017 21:44:31 +0800 Subject: [PATCH 03/41] loops --- src/tutorial/Loops.java | 81 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/tutorial/Loops.java diff --git a/src/tutorial/Loops.java b/src/tutorial/Loops.java new file mode 100644 index 0000000..33793d2 --- /dev/null +++ b/src/tutorial/Loops.java @@ -0,0 +1,81 @@ +/** + * Created by Oliver on 25/06/2017. + */ +public class Loops { + public static void test_while() { + System.out.println("*****while*****"); + int x = 1; + while (x < 10) { + System.out.println("x in while: " + x); + x++; + } + } + + public static void test_do_while() { + System.out.println("*****do while*****"); + int x = 10; + do { + System.out.println("x in do while: " + x); + x++; + } while (x < 10); + } + + public static void test_for() { + System.out.println("*****for*****"); + for (int x = 10; x < 20; x++) { + System.out.println("x in for: " + x); + } + } + + public static void test_enhanced_for() { + System.out.println("*****enhanced for*****"); + int[] numbers = {20, 21, 22, 23, 24}; + for (int x : numbers) { + System.out.println("x in enhanced for: " + x); + } + } + + public static void test_break() { + System.out.println("*****break*****"); + int[] numbers = {25, 26, 27, 28, 29, 30}; + for (int x : numbers) { + if (x == 27) { + break; + } + System.out.println("x in break: " + x); + } + + } + + public static void test_continue() { + System.out.println("*****continue*****"); + int[] numbers = {31, 32, 33, 34, 35}; + for (int x : numbers) { + if (x == 33) { + continue; + } + System.out.println("x in continue: " + x); + + } + } + + public static void test_nested_for() { + System.out.println("*****nested for*****"); + for (int x = 1; x <= 9; x++) { + for (int y = 1; y <= 9; y++) { + System.out.print(x + "x" + y + "=" + x * y + "\t"); + } + System.out.println(); + } + } + + public static void main(String[] args) { + test_while(); + test_do_while(); + test_for(); + test_enhanced_for(); + test_break(); + test_continue(); + test_nested_for(); + } +} From bc5738e3510fb0241e71bc2492da742300c254ed Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Mon, 26 Jun 2017 00:04:19 +0800 Subject: [PATCH 04/41] IfElseSwitch, Numbers --- src/tutorial/IfElseSwitch.java | 42 ++++++++++ src/tutorial/Numbers.java | 148 +++++++++++++++++++++++++++++++++ 2 files changed, 190 insertions(+) create mode 100644 src/tutorial/IfElseSwitch.java create mode 100644 src/tutorial/Numbers.java diff --git a/src/tutorial/IfElseSwitch.java b/src/tutorial/IfElseSwitch.java new file mode 100644 index 0000000..d07d2b8 --- /dev/null +++ b/src/tutorial/IfElseSwitch.java @@ -0,0 +1,42 @@ +/** + * Created by Oliver on 25/06/2017. + */ +public class IfElseSwitch { + public static void test_if_else() { + int x = 10; + if (x < 10) { + System.out.println("x is a low number"); + } else if (x > 10 && x < 50) { + System.out.println("x is a medium number"); + } else if (x > 50 && x < 100) { + System.out.println("x is a high number"); + } else { + System.out.println("x is out of range"); + } + } + + public static void test_switch() { + String grade = "B"; + switch (grade) { + case "A": + System.out.println("Excellent grade"); + break; + case "B": + System.out.println("Good grade"); + break; + case "C": + System.out.println("Mediocre grade"); + break; + default: + System.out.println("It's not good"); + + } + } + + + public static void main(String[] args) { + test_if_else(); + test_switch(); + } + +} diff --git a/src/tutorial/Numbers.java b/src/tutorial/Numbers.java new file mode 100644 index 0000000..c35bceb --- /dev/null +++ b/src/tutorial/Numbers.java @@ -0,0 +1,148 @@ +import java.util.Random; + +/** + * Created by Oliver on 25/06/2017. + */ +public class Numbers { + public static void test_numbers() { + // 当 x 被赋为整型值时,由于x是一个对象,所以编译器要对x进行装箱。然后,为了使x能进行加运算,所以要对x进行拆箱 + System.out.println("*****number*****"); + Integer x = 5; + x++; + System.out.println(x); + + } + + public static void test_xxxValue() { + // xxxValue() 方法用于将 Number 对象转换为 xxx 数据类型的值并返回 + System.out.println("*****xxxValue(拆箱)*****"); + Integer x = 5; + // 返回 byte 原生数据类型 + System.out.println("byteValue: " + x.byteValue()); + + // 返回 double 原生数据类型 + System.out.println("doubleValue: " + x.doubleValue()); + + // 返回 long 原生数据类型 + System.out.println("longValue: " + x.longValue()); + } + + public static void test_compareTo() { + System.out.println("*****compareTo*****"); + Integer x = 5; + System.out.println("5 compared to 3: " + x.compareTo(3)); + System.out.println("5 compared to 8: " + x.compareTo(8)); + System.out.println("5 compared to 5: " + x.compareTo(5)); + } + + public static void test_equals() { + /** + 注意 == 与 equals的区别 + == 它比较的是对象的地址 + equals 比较的是对象的内容 + */ + System.out.println("*****equals*****"); + Integer x = 5; + Integer y = 10; + Integer z = 5; + short s = 5; + System.out.println("Integer 5 equals Integer 10: " + x.equals(y)); + System.out.println("Integer 5 equals Integer 5: " + x.equals(z)); + System.out.println("Integer 5 equals short 5: " + x.equals(s)); + } + + public static void test_valueOf() { + // valueOf() 方法用于返回给定参数的原生 Number 对象值,参数可以是原生数据类型, String等 + System.out.println("*****valueOf(装箱)*****"); + Integer x = Integer.valueOf(9); + Double c = Double.valueOf(5); + Float f = Float.valueOf("80"); + Integer b = Integer.valueOf("444", 16); // 使用 16 进制 + System.out.println(x); + System.out.println(c); + System.out.println(f); + System.out.println(b); + + } + + public static void test_toString() { + System.out.println("*****toString*****"); + Integer x = 5; + System.out.println("5 toString: " + x.toString()); + System.out.println("Integer.toString(8): " + Integer.toString(8)); + + } + + public static void test_parseInt() { + // parseInt() 方法用于将字符串参数作为有符号的十进制整数进行解析。 + System.out.println("*****parseInt*****"); + System.out.println("Integer.parseInt('19'): " + Integer.parseInt("19")); + System.out.println("Double.parseDouble('29'): " + Double.parseDouble("29")); + System.out.println("Integer.parseInt('444', 16): " + Integer.parseInt("444", 16)); + } + + public static void test_math() { + // Math 的方法都被定义为 static 形式,通过 Math 类可以在主函数中直接调用 + System.out.println("*****math*****"); + System.out.println("90 度的正弦值:" + Math.sin(Math.PI / 2)); + System.out.println("0度的余弦值:" + Math.cos(0)); + System.out.println("60度的正切值:" + Math.tan(Math.PI / 3)); + System.out.println("1的反正切值: " + Math.atan(1)); + System.out.println("π/2的角度值:" + Math.toDegrees(Math.PI / 2)); + System.out.println(Math.PI); + } + + public static void test_abs() { + System.out.println("*****abs*****"); + Integer x = -4; + Float y = -1f; + Double z = -2d; + System.out.println("Math.abs(-4): " + Math.abs(x)); + System.out.println("Math.abs(-1f): " + Math.abs(y)); + System.out.println("Math.abs(-2d): " + Math.abs(z)); + } + + public static void test_ceil_floor_rint() { + System.out.println("*****ceil*****"); + System.out.println("Math.ceil(100.675): " + Math.ceil(100.675)); + System.out.println("Math.ceil(-90.1): " + Math.ceil(-90.1)); + System.out.println("Math.floor(100.675)" + Math.floor(100.675)); + System.out.println("Math.floor(-90.1)" + Math.floor(-90.1)); + // 返回与参数最接近的整数。返回类型为double + System.out.println("Math.rint(100.675): " + Math.rint(100.675)); + System.out.println("Math.rint(100.5): " + Math.rint(100.5)); + System.out.println("Math.rint(100.200): " + Math.rint(100.200)); + // 返回一个最接近的int、long型值 + System.out.println("Math.round(100.675): " + Math.round(100.675)); + System.out.println("Math.round(100.5): " + Math.round(100.5)); + System.out.println("Math.round(100.200): " + Math.round(100.200)); + + System.out.println("Math.min(12.123, 12.456): " + Math.min(12.123, 12.456)); + System.out.println("Math.min(11, 12): " + Math.min(11, 12)); + System.out.println("Math.max(12.123, 12.456): " + Math.max(12.123, 12.456)); + System.out.println("Math.max(11, 12): " + Math.max(11, 12)); + + double x = 11.635; + double y = 2.76; + System.out.printf("Math.E: %.4f%n", Math.E); + System.out.printf("Math.pow(%.3f, %.3f): %.3f%n", x, y, Math.pow(x, y)); + + System.out.printf("Math.random(): %.3f%n", Math.random()); + Random random = new Random(); + System.out.println("Random 0~99: " + random.nextInt(100)); + } + + public static void main(String[] args) { + test_numbers(); + test_math(); + test_xxxValue(); + test_compareTo(); + test_equals(); + test_valueOf(); + test_toString(); + test_parseInt(); + test_abs(); + test_ceil_floor_rint(); + } + +} From 16b5110eae1e18e7365d99e81961dfd927ec9305 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Mon, 26 Jun 2017 22:51:05 +0800 Subject: [PATCH 05/41] Character, String --- src/tutorial/Characters.java | 57 +++++++++++ src/tutorial/Numbers.java | 27 +++-- src/tutorial/Strings.java | 193 +++++++++++++++++++++++++++++++++++ 3 files changed, 263 insertions(+), 14 deletions(-) create mode 100644 src/tutorial/Characters.java create mode 100644 src/tutorial/Strings.java diff --git a/src/tutorial/Characters.java b/src/tutorial/Characters.java new file mode 100644 index 0000000..ae2a6c4 --- /dev/null +++ b/src/tutorial/Characters.java @@ -0,0 +1,57 @@ +/** + * Created by Oliver on 26/06/2017. + */ +public class Characters { + public static void Character_isLetter() { + System.out.println("'C' isLetter: " + Character.isLetter('C')); + System.out.println("'1' isLetter: " + Character.isLetter('1')); + } + + public static void Character_isDigit() { + System.out.println("'A' isDigit: " + Character.isDigit('A')); + System.out.println("'5' isDigit: " + Character.isDigit('5')); + } + + public static void Character_isWhitespace() { + System.out.println("'c' is Whitespace: " + Character.isWhitespace('c')); + System.out.println("'\\t' is Whitespace: " + Character.isWhitespace('\t')); + System.out.println("'\\n' is Whitespace: " + Character.isWhitespace('\n')); + System.out.println("' ' is Whitespace: " + Character.isWhitespace(' ')); + } + + public static void Character_isUpperCase() { + System.out.println("'A' isUpperCase: " + Character.isUpperCase('A')); + System.out.println("'a' isUpperCase: " + Character.isUpperCase('a')); + } + + public static void Character_isLowerCase() { + System.out.println("'B' isLowerCase: " + Character.isLowerCase('A')); + System.out.println("'b' isLowerCase: " + Character.isLowerCase('b')); + } + + public static void Character_toUpperCase() { + System.out.println("'E' toUpperCase: " + Character.toUpperCase('E')); + System.out.println("'e' toUpperCase: " + Character.toUpperCase('e')); + } + + public static void Character_toLowerCase() { + System.out.println("'E' toLowerCase: " + Character.toLowerCase('E')); + System.out.println("'e' toLowerCase: " + Character.toLowerCase('e')); + } + + public static void Character_toString() { + System.out.println("'t' toString: " + Character.toString('t')); + System.out.println("'7' toString: " + Character.toString('7')); + } + + public static void main(String[] args) { + Character_isLetter(); + Character_isDigit(); + Character_isWhitespace(); + Character_isUpperCase(); + Character_isLowerCase(); + Character_toUpperCase(); + Character_toLowerCase(); + Character_toString(); + } +} diff --git a/src/tutorial/Numbers.java b/src/tutorial/Numbers.java index c35bceb..907defe 100644 --- a/src/tutorial/Numbers.java +++ b/src/tutorial/Numbers.java @@ -13,6 +13,19 @@ public static void test_numbers() { } + public static void test_valueOf() { + // valueOf() 方法用于返回给定参数的原生 Number 对象值,参数可以是原生数据类型, String等 + System.out.println("*****valueOf(装箱)*****"); + Integer x = Integer.valueOf(9); + Double c = Double.valueOf(5); + Float f = Float.valueOf("80"); + Integer b = Integer.valueOf("444", 16); // 使用 16 进制 + System.out.println(x); + System.out.println(c); + System.out.println(f); + System.out.println(b); + } + public static void test_xxxValue() { // xxxValue() 方法用于将 Number 对象转换为 xxx 数据类型的值并返回 System.out.println("*****xxxValue(拆箱)*****"); @@ -51,20 +64,6 @@ public static void test_equals() { System.out.println("Integer 5 equals short 5: " + x.equals(s)); } - public static void test_valueOf() { - // valueOf() 方法用于返回给定参数的原生 Number 对象值,参数可以是原生数据类型, String等 - System.out.println("*****valueOf(装箱)*****"); - Integer x = Integer.valueOf(9); - Double c = Double.valueOf(5); - Float f = Float.valueOf("80"); - Integer b = Integer.valueOf("444", 16); // 使用 16 进制 - System.out.println(x); - System.out.println(c); - System.out.println(f); - System.out.println(b); - - } - public static void test_toString() { System.out.println("*****toString*****"); Integer x = 5; diff --git a/src/tutorial/Strings.java b/src/tutorial/Strings.java new file mode 100644 index 0000000..097c1de --- /dev/null +++ b/src/tutorial/Strings.java @@ -0,0 +1,193 @@ +/** + * Created by Oliver on 26/06/2017. + */ +public class Strings { + public static void String_length() { + String site = "www.google.com"; + System.out.printf("Length of site is %d%n", site.length()); + } + + public static void String_concat() { + String a = "Hello, "; + System.out.println(a.concat("Java")); + } + + public static void String_format() { + String s = String.format("浮点型变量的的值为 " + + "%f, 整型变量的值为 " + + "%d, 字符串变量的值为 " + + "%s", 1.23, 2, "Java"); + System.out.println(s); + } + + public static void String_charAt() { + System.out.println("'ABC'.charAt(1): " + "ABC".charAt(1)); + } + + public static void String_compareTo() { + System.out.println("ABC compareTo ABC: " + "ABC".compareTo("ABC")); + System.out.println("ABC compareTo ABC123: " + "ABC".compareTo("ABC123")); + System.out.println("ABC123 compareTo ABC: " + "ABC123".compareTo("ABC")); + System.out.println("ABC compareToIgnoreCase abc: " + "ABC".compareToIgnoreCase("abc")); + } + + public static void String_contentEquals() { + // 用于将将此字符串与指定的 StringBuffer 比较 + StringBuffer buffer = new StringBuffer("abc"); + System.out.println("ABC contentEquals StringBuffer(\"abc\"): " + "ABC".contentEquals(buffer)); + System.out.println("abc contentEquals StringBuffer(\"abc\"): " + "abc".contentEquals(buffer)); + } + + public static void String_copyValueOf() { + char[] c = {'G', 'o', 'o', 'g', 'l', 'e'}; + String s = ""; + System.out.println("copyValueOf({'G', 'o', 'o', 'g', 'l', 'e'}): " + s.copyValueOf(c)); + System.out.println("copyValueOf({'G', 'o', 'o', 'g', 'l', 'e'}, 1, 3): " + s.copyValueOf(c, 1, 3)); + System.out.println("valueOf({'G', 'o', 'o', 'g', 'l', 'e'}): " + s.valueOf(c)); + } + + public static void String_endsWith() { + System.out.println("Google endsWith e: " + "Google".endsWith("e")); + System.out.println("Google endsWith G: " + "Google".endsWith("G")); + } + + public static void String_equals() { + System.out.println("Google equals Google: " + "Google".equals("Google")); + System.out.println("Google equals google: " + "Google".equals("google")); + System.out.println("Google equalsIgnoreCase google: " + "Google".equalsIgnoreCase("google")); + } + + public static void String_getChars() { + // 将字符从此字符串复制到目标字符数组 + String s = new String("Google"); + char[] c = new char[10]; + s.getChars(1, 4, c, 0); + System.out.println(c); + } + + public static void String_hashCode() { + /* + 字符串对象的哈希码根据以下公式计算: + s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] + 使用 int 算法,这里 s[i] 是字符串的第 i 个字符,n 是字符串的长度,^ 表示求幂。空字符串的哈希值为 0 + */ + System.out.println("www.runoob.com hashCode: " + "www.runoob.com".hashCode()); + } + + public static void String_indexOf() { + System.out.println("Google indexOf('o'): " + "Google".indexOf('o')); + System.out.println("Google indexOf('g') fromIndex 2: " + "Google".indexOf('g', 2)); + System.out.println("Google indexOf('gle'): " + "Google".indexOf("gle")); + System.out.println("Google indexOf('gle' fromIndex 2): " + "Google".indexOf("gle", 2)); + } + + public static void String_lastIndexOf() { + System.out.println("Google lastIndexIf('o'): " + "Google".lastIndexOf('o')); + System.out.println("Google lastIndexIf('oog'): " + "Google".lastIndexOf("oog")); + } + + public static void String_matches() { + System.out.println("Google matches('(.*)oog(.*)'): " + "Google".matches("(.*)oog(.*)")); + /* 检测两个字符串在一个区域内是否相等 + ignoreCase -- 如果为 true,则比较字符时忽略大小写。 + toffset -- 此字符串中子区域的起始偏移量。 + other -- 字符串参数。 + ooffset -- 字符串参数中子区域的起始偏移量。 + len -- 要比较的字符数。 + */ + System.out.println("Google regionMatches(1, 'oog', 0, 3): " + "Google".regionMatches(1, "oog", 0, 3)); + System.out.println("Google regionMatches(ignoreCase, 1, 'oog', 0, 3): " + "Google".regionMatches(true, 1, "OOG", 0, 3)); + } + + public static void String_replace() { + System.out.println("Google replace o to O: " + "Google".replace('o', 'O')); + System.out.println("Google replaceAll to Apple: " + "Google".replaceAll("(.*)oog(.*)", "Apple")); + System.out.println("Google failed to replaceAll to Apple: " + "Google".replaceAll("(,*)OOG(.*)", "Apple")); + System.out.println("Google replaceFirst o to O: " + "Google".replaceFirst("o", "O")); + } + + public static void String_split() { + System.out.println("- 分隔符返回值 :"); + for (String name : "www-google-com".split("-")) { + System.out.println(name); + } + System.out.println("- 分隔符设置分割份数返回值 :"); + for (String name : "www-google-com".split("-", 2)) { + System.out.println(name); + } + System.out.println("转义字符返回值 :"); + for (String name : "www.google.com".split("\\.")) { + System.out.println(name); + } + System.out.println("多个分隔符返回值 :"); + for (String name : "www.google-com".split("\\.|-")) { + System.out.println(name); + } + } + + public static void String_startsWith() { + System.out.println("www.google.com startsWith www: " + "www.google.com".startsWith("www")); + System.out.println("www.google.com startsWith com: " + "www.google.com".startsWith("com")); + System.out.println("www.google.com startsWith com offset 11: " + "www.google.com".startsWith("com", 11)); + } + + public static void String_subSequence() { + System.out.println("www.google.com subSequence(4, 10): " + "www.google.com".subSequence(4, 10)); + } + + public static void String_subString() { + System.out.println("www.google.com subString(4): " + "www.google.com".substring(4)); + System.out.println("www.google.com subString(4, 10): " + "www.google.com".substring(4, 10)); + } + + public static void String_toCharArray() { + System.out.println("将此字符串转换为一个新的字符数组 :"); + String s = new String("google"); + for (char c : s.toCharArray()) { + System.out.print(c); + } + } + + public static void String_toLowerCase() { + System.out.println("AMD toLowerCase: " + "AMD".toLowerCase()); + } + + public static void String_toString() { + System.out.println("hao123 toString: " + "hao123".toString()); + } + + public static void String_toUpperCase() { + System.out.println("apple toUpperCase: " + "apple".toUpperCase()); + } + + public static void String_trim() { + System.out.println("' google ' trim: " + " google ".trim()); + } + + public static void main(String[] args) { + String_length(); + String_concat(); + String_format(); + String_charAt(); + String_compareTo(); + String_contentEquals(); + String_copyValueOf(); + String_endsWith(); + String_equals(); + String_getChars(); + String_hashCode(); + String_indexOf(); + String_lastIndexOf(); + String_matches(); + String_replace(); + String_split(); + String_startsWith(); + String_subSequence(); + String_subString(); + String_toCharArray(); + String_toLowerCase(); + String_toString(); + String_toUpperCase(); + String_trim(); + } +} From 0a8bd0d4fca55b557c6a606906dec0e84a1039c7 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Mon, 26 Jun 2017 23:13:23 +0800 Subject: [PATCH 06/41] StringBuffer --- src/tutorial/StringBuffers.java | 38 +++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/tutorial/StringBuffers.java diff --git a/src/tutorial/StringBuffers.java b/src/tutorial/StringBuffers.java new file mode 100644 index 0000000..ab9bee1 --- /dev/null +++ b/src/tutorial/StringBuffers.java @@ -0,0 +1,38 @@ +/** + * Created by Oliver on 26/06/2017. + */ +public class StringBuffers { + public static void StringBuffer_append() { + StringBuffer buffer = new StringBuffer("Google"); + buffer.append(".com"); + System.out.println("StringBuffer 'Google' append '.com': " + buffer); + } + + public static void StringBuffer_reverse() { + StringBuffer buffer = new StringBuffer("apple"); + System.out.println("StringBuffer 'apple' reverse: " + buffer.reverse()); + } + + public static void StringBuffer_delete() { + StringBuffer buffer = new StringBuffer("apple"); + System.out.println("StringBuffer 'apple' delete(2, 4): " + buffer.delete(2, 4)); + } + + public static void StringBuffer_insert() { + StringBuffer buffer = new StringBuffer("apple"); + System.out.println("StringBuffer 'apple' insert(3, '-'): " + buffer.insert(3, '-')); + } + + public static void StringBuffer_replace() { + StringBuffer buffer = new StringBuffer("google"); + System.out.println("StringBuffer 'google' replace(1, 3, 'OO'): " + buffer.replace(1, 3, "OO")); + } + + public static void main(String[] args) { + StringBuffer_append(); + StringBuffer_reverse(); + StringBuffer_delete(); + StringBuffer_insert(); + StringBuffer_replace(); + } +} From 0a94b2eb92e90f2cccd39570595828e69bab5e4c Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Tue, 27 Jun 2017 18:31:54 +0800 Subject: [PATCH 07/41] Array --- src/tutorial/Arrays.java | 53 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/tutorial/Arrays.java diff --git a/src/tutorial/Arrays.java b/src/tutorial/Arrays.java new file mode 100644 index 0000000..cd4a495 --- /dev/null +++ b/src/tutorial/Arrays.java @@ -0,0 +1,53 @@ +/** + * Created by Oliver on 27/06/2017. + */ +public class Arrays { + public static void Array_for() { + double[] myList = {1.9, 2.9, 3.4, 3.5}; + for (int i = 0; i < myList.length; i++) { + System.out.println(myList[i]); + } + + double total = 0d; + for (int i = 0; i < myList.length; i++) { + total += myList[i]; + } + System.out.println("Total: " + total); + + double max = myList[0]; + for (int i = 0; i < myList.length; i++) { + max = Math.max(myList[i], max); + } + System.out.println("Max: " + max); + } + + public static void Array_foreach() { + double[] myList = {1.9, 2.9, 3.4, 3.5}; + for (double item : myList) { + System.out.println(item); + } + } + + public static int[] reverse(int[] array) { + int[] result = new int[array.length]; + for (int i = 0, j = result.length - 1; i < array.length; i++, j--) { + result[i] = array[j]; + } + return result; + } + + public static void Array_reverse() { + int[] arr = {1, 2, 3, 4, 5}; + int[] reversed = reverse(arr); + for (int i : reversed) { + System.out.println(i); + } + } + + public static void main(String[] args) { + Array_for(); + Array_foreach(); + Array_reverse(); + } + +} From 9d34e53c30829f4d0ca7fe4d1dbd271d4a5fc441 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Wed, 28 Jun 2017 01:01:28 +0800 Subject: [PATCH 08/41] Date --- src/tutorial/Dates.java | 134 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 src/tutorial/Dates.java diff --git a/src/tutorial/Dates.java b/src/tutorial/Dates.java new file mode 100644 index 0000000..b80545f --- /dev/null +++ b/src/tutorial/Dates.java @@ -0,0 +1,134 @@ +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +/** + * Created by Oliver on 27/06/2017. + */ +public class Dates { + public static void Date_date() { + Date date = new Date(); + System.out.println("date: " + date); + } + + public static void Date_getTime() { + Date date = new Date(); + System.out.println("date.getTime: " + date.getTime()); + } + + public static void Date_SimpleDateFormat() throws ParseException { + /* + G 纪元标记 AD + y 四位年份 2001 + M 月份 July or 07 + d 一个月的日期 10 + h A.M./P.M. (1~12)格式小时 12 + H 一天中的小时 (0~23) 22 + m 分钟数 30 + s 秒数 55 + S 毫秒数 234 + E 星期几 Tuesday + D 一年中的日子 360 + F 一个月中第几周的周几 2 (second Wed. in July) + w 一年中第几周 40 + W 一个月中第几周 1 + a A.M./P.M. 标记 PM + k 一天中的小时(1~24) 24 + K A.M./P.M. (0~11)格式小时 10 + z 时区 Eastern Standard Time + ' 文字定界符 Delimiter + " 单引号 ` + */ + Date date = new Date(); + SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); + System.out.println("SimpleDateFormat.format(): " + ft.format(date)); + + SimpleDateFormat ft2 = new SimpleDateFormat("yyyy-MM-dd"); + try { + Date t = ft2.parse("1983-07-14"); + System.out.println(t); + } catch (ParseException e) { + System.out.println("Unparsable using " + ft2); + } + } + + public static void Date_printf() { + /* + c 包括全部日期和时间信息 星期六 十月 27 14:21:20 CST 2007 + F "年-月-日"格式 2007-10-27 + D "月/日/年"格式 10/27/07 + r "HH:MM:SS PM"格式(12时制) 02:25:51 下午 + T "HH:MM:SS"格式(24时制) 14:28:16 + R "HH:MM"格式(24时制) 14:28 + */ + Date date = new Date(); + System.out.printf("全部日期和时间信息: %tc%n", date); + System.out.printf("\"年-月-日\"格式: %tF%n", date); + System.out.printf("\"月/日/年\"格式: %tD%n", date); + System.out.printf("\"HH:MM:SS PM\"格式(12时制): %tr%n", date); + System.out.printf("\"HH:MM:SS\"格式(24时制): %tT%n", date); + System.out.printf("\"HH:MM\"格式(24时制): %tR%n", date); + + // 用一个格式化字符串指出要被格式化的参数的索引, 索引必须紧跟在%后面,而且必须以$结束 + System.out.printf("%1$s %2$tB %2$td, %2$tY%n", "Due date:", date); + // 使用 < 标志, 它表明先前被格式化的参数要被再次使用 + System.out.printf("%s %tB % Date: Wed, 28 Jun 2017 10:15:32 +0800 Subject: [PATCH 09/41] Calendar --- src/tutorial/Calendars.java | 67 +++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/tutorial/Calendars.java diff --git a/src/tutorial/Calendars.java b/src/tutorial/Calendars.java new file mode 100644 index 0000000..24dc638 --- /dev/null +++ b/src/tutorial/Calendars.java @@ -0,0 +1,67 @@ +import java.util.Calendar; +import java.util.GregorianCalendar; + +/** + * Created by Oliver on 28/06/2017. + */ +public class Calendars { + public static void Calendar_set() { + Calendar c = Calendar.getInstance(); //默认是当前日期 + System.out.println("Calendar.getInstance: " + c); + + c.set(2009, 6 - 1, 12); + System.out.println("Calendar.set(2009, 5, 12): " + c); + + c.set(Calendar.DATE, 10); + System.out.println("Calendar.set(Calendar.DATE, 10): " + c.get(Calendar.DATE)); + + c.set(Calendar.YEAR, 2008); + System.out.println("Calendar.set(Calendar.YEAR, 2008): " + c.get(Calendar.YEAR)); + } + + public static void Calendar_add() { + Calendar c = Calendar.getInstance(); + + c.add(Calendar.YEAR, 10); + System.out.println("Calendar.add(Calendar.YEAR, 10): " + c.get(Calendar.YEAR)); + + c.add(Calendar.DATE, -10); + System.out.println("Calendar.add(Calendar.DATE, -10): " + c.get(Calendar.DATE)); + } + + public static void Gregorian_calendar() { + String months[] = { + "Jan", "Feb", "Mar", "Apr", + "May", "Jun", "Jul", "Aug", + "Sep", "Oct", "Nov", "Dec"}; + + int year; + // 初始化 Gregorian 日历 + // 使用当前时间和日期 + // 默认为本地时间和时区 + GregorianCalendar gcalendar = new GregorianCalendar(); + // 显示当前时间和日期的信息 + System.out.print("Date: "); + System.out.print(months[gcalendar.get(Calendar.MONTH)]); + System.out.print(" " + gcalendar.get(Calendar.DATE) + " "); + System.out.println(year = gcalendar.get(Calendar.YEAR)); + System.out.print("Time: "); + System.out.print(gcalendar.get(Calendar.HOUR) + ":"); + System.out.print(gcalendar.get(Calendar.MINUTE) + ":"); + System.out.println(gcalendar.get(Calendar.SECOND)); + + // 测试当前年份是否为闰年 + if (gcalendar.isLeapYear(year)) { + System.out.println("当前年份是闰年"); + } else { + System.out.println("当前年份不是闰年"); + } + } + + public static void main(String[] args) { + Calendar_set(); + Calendar_add(); + Gregorian_calendar(); + } + +} From c4b11ba21ed34448c31b9f6603aa29b899d79d97 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Wed, 28 Jun 2017 13:53:28 +0800 Subject: [PATCH 10/41] Regex --- src/tutorial/Regexes.java | 129 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 src/tutorial/Regexes.java diff --git a/src/tutorial/Regexes.java b/src/tutorial/Regexes.java new file mode 100644 index 0000000..911949a --- /dev/null +++ b/src/tutorial/Regexes.java @@ -0,0 +1,129 @@ +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Created by Oliver on 28/06/2017. + */ +public class Regexes { + /* 正则表达式语法: + \ 将下一字符标记为特殊字符、文本、反向引用或八进制转义符。例如,"n"匹配字符"n"。"\n"匹配换行符。序列"\\"匹配"\","\("匹配"("。 + ^ 匹配输入字符串开始的位置。如果设置了 RegExp 对象的 Multiline 属性,^ 还会与"\n"或"\r"之后的位置匹配。 + $ 匹配输入字符串结尾的位置。如果设置了 RegExp 对象的 Multiline 属性,$ 还会与"\n"或"\r"之前的位置匹配。 + * 零次或多次匹配前面的字符或子表达式。例如,zo* 匹配"z"和"zoo"。* 等效于 {0,}。 + + 一次或多次匹配前面的字符或子表达式。例如,"zo+"与"zo"和"zoo"匹配,但与"z"不匹配。+ 等效于 {1,}。 + ? 零次或一次匹配前面的字符或子表达式。例如,"do(es)?"匹配"do"或"does"中的"do"。? 等效于 {0,1}。 + {n} n 是非负整数。正好匹配 n 次。例如,"o{2}"与"Bob"中的"o"不匹配,但与"food"中的两个"o"匹配。 + {n,} n 是非负整数。至少匹配 n 次。例如,"o{2,}"不匹配"Bob"中的"o",而匹配"foooood"中的所有 o。"o{1,}"等效于"o+"。"o{0,}"等效于"o*"。 + {n,m} M 和 n 是非负整数,其中 n <= m。匹配至少 n 次,至多 m 次。例如,"o{1,3}"匹配"fooooood"中的头三个 o。'o{0,1}' 等效于 'o?'。注意:您不能将空格插入逗号和数字之间。 + ? 当此字符紧随任何其他限定符(*、+、?、{n}、{n,}、{n,m})之后时,匹配模式是"非贪心的"。"非贪心的"模式匹配搜索到的、尽可能短的字符串,而默认的"贪心的"模式匹配搜索到的、尽可能长的字符串。例如,在字符串"oooo"中,"o+?"只匹配单个"o",而"o+"匹配所有"o"。 + . 匹配除"\r\n"之外的任何单个字符。若要匹配包括"\r\n"在内的任意字符,请使用诸如"[\s\S]"之类的模式。 + (pattern) 匹配 pattern 并捕获该匹配的子表达式。可以使用 $0…$9 属性从结果"匹配"集合中检索捕获的匹配。若要匹配括号字符 ( ),请使用"\("或者"\)"。 + (?:pattern) 匹配 pattern 但不捕获该匹配的子表达式,即它是一个非捕获匹配,不存储供以后使用的匹配。这对于用"or"字符 (|) 组合模式部件的情况很有用。例如,'industr(?:y|ies) 是比 'industry|industries' 更经济的表达式。 + (?=pattern) 执行正向预测先行搜索的子表达式,该表达式匹配处于匹配 pattern 的字符串的起始点的字符串。它是一个非捕获匹配,即不能捕获供以后使用的匹配。例如,'Windows (?=95|98|NT|2000)' 匹配"Windows 2000"中的"Windows",但不匹配"Windows 3.1"中的"Windows"。预测先行不占用字符,即发生匹配后,下一匹配的搜索紧随上一匹配之后,而不是在组成预测先行的字符后。 + (?!pattern) 执行反向预测先行搜索的子表达式,该表达式匹配不处于匹配 pattern 的字符串的起始点的搜索字符串。它是一个非捕获匹配,即不能捕获供以后使用的匹配。例如,'Windows (?!95|98|NT|2000)' 匹配"Windows 3.1"中的 "Windows",但不匹配"Windows 2000"中的"Windows"。预测先行不占用字符,即发生匹配后,下一匹配的搜索紧随上一匹配之后,而不是在组成预测先行的字符后。 + x|y 匹配 x 或 y。例如,'z|food' 匹配"z"或"food"。'(z|f)ood' 匹配"zood"或"food"。 + [xyz] 字符集。匹配包含的任一字符。例如,"[abc]"匹配"plain"中的"a"。 + [^xyz] 反向字符集。匹配未包含的任何字符。例如,"[^abc]"匹配"plain"中"p","l","i","n"。 + [a-z] 字符范围。匹配指定范围内的任何字符。例如,"[a-z]"匹配"a"到"z"范围内的任何小写字母。 + [^a-z] 反向范围字符。匹配不在指定的范围内的任何字符。例如,"[^a-z]"匹配任何不在"a"到"z"范围内的任何字符。 + \b 匹配一个字边界,即字与空格间的位置。例如,"er\b"匹配"never"中的"er",但不匹配"verb"中的"er"。 + \B 非字边界匹配。"er\B"匹配"verb"中的"er",但不匹配"never"中的"er"。 + \cx 匹配 x 指示的控制字符。例如,\cM 匹配 Control-M 或回车符。x 的值必须在 A-Z 或 a-z 之间。如果不是这样,则假定 c 就是"c"字符本身。 + \d 数字字符匹配。等效于 [0-9]。 + \D 非数字字符匹配。等效于 [^0-9]。 + \f 换页符匹配。等效于 \x0c 和 \cL。 + \n 换行符匹配。等效于 \x0a 和 \cJ。 + \r 匹配一个回车符。等效于 \x0d 和 \cM。 + \s 匹配任何空白字符,包括空格、制表符、换页符等。与 [ \f\n\r\t\v] 等效。 + \S 匹配任何非空白字符。与 [^ \f\n\r\t\v] 等效。 + \t 制表符匹配。与 \x09 和 \cI 等效。 + \v 垂直制表符匹配。与 \x0b 和 \cK 等效。 + \w 匹配任何字类字符,包括下划线。与"[A-Za-z0-9_]"等效。 + \W 与任何非单词字符匹配。与"[^A-Za-z0-9_]"等效。 + \xn 匹配 n,此处的 n 是一个十六进制转义码。十六进制转义码必须正好是两位数长。例如,"\x41"匹配"A"。"\x041"与"\x04"&"1"等效。允许在正则表达式中使用 ASCII 代码。 + \num 匹配 num,此处的 num 是一个正整数。到捕获匹配的反向引用。例如,"(.)\1"匹配两个连续的相同字符。 + \n 标识一个八进制转义码或反向引用。如果 \n 前面至少有 n 个捕获子表达式,那么 n 是反向引用。否则,如果 n 是八进制数 (0-7),那么 n 是八进制转义码。 + \nm 标识一个八进制转义码或反向引用。如果 \nm 前面至少有 nm 个捕获子表达式,那么 nm 是反向引用。如果 \nm 前面至少有 n 个捕获,则 n 是反向引用,后面跟有字符 m。如果两种前面的情况都不存在,则 \nm 匹配八进制值 nm,其中 n 和 m 是八进制数字 (0-7)。 + \nml 当 n 是八进制数 (0-3),m 和 l 是八进制数 (0-7) 时,匹配八进制转义码 nml。 + \un 匹配 n,其中 n 是以四位十六进制数表示的 Unicode 字符。例如,\u00A9 匹配版权符号 (©)。 + */ + + public static void Regex_Pattern_matches() { + String content = "www.google.com"; + String pattern = "^w.*google.*"; + boolean isMatch = Pattern.matches(pattern, content); + System.out.printf("'www.google.com' matches '^w.*google.*': %b%n", isMatch); + } + + public static void Regex_Matcher_group() { + String line = "This order was placed for QT3000! OK?"; + Pattern p = Pattern.compile("(\\D+)(\\d+)(.*)"); // 使用两个反斜线,表示正则表达式受到保护,不被 Java 字节码编译器解释 + Matcher m = p.matcher(line); + if (m.find()) { + System.out.println("Matcher.group(0): " + m.group(0)); + System.out.println("Matcher.group(1): " + m.group(1)); + System.out.println("Matcher.group(2): " + m.group(2)); + System.out.println("Matcher.group(3): " + m.group(3)); + System.out.println("Matcher.groupCount(): " + m.groupCount()); + } + } + + public static void Regex_Matcher_start_end() { + String content = "Java PythonJava Java1 Java"; + Pattern p = Pattern.compile("\\bJava\\b"); + Matcher m = p.matcher(content); + int count = 0; + while (m.find()) { + count++; + System.out.println("Count: " + count); + System.out.println("start: " + m.start()); + System.out.println("end: " + m.end()); + } + } + + public static void Regex_Matcher_lookingAt() { + String content1 = "Java PythonJava"; + String content2 = "Python PythonJava"; + + Pattern p = Pattern.compile("Java"); + Matcher m1 = p.matcher(content1); + Matcher m2 = p.matcher(content2); + // lookingAt 方法虽然不需要整句都匹配,但是需要从第一个字符开始匹配。 + System.out.println("Matcher.lookingAt: " + m1.lookingAt()); + System.out.println("Matcher.lookingAt: " + m2.lookingAt()); + // matches 要求整个序列都匹配 + System.out.println("Matcher.matches: " + m1.matches()); + } + + public static void Regex_Matcher_replaceFirst_replaceAll() { + String content = "Java PythonJava"; + Pattern p = Pattern.compile("Java"); + Matcher m = p.matcher(content); + String replaceFirst = m.replaceFirst("Ruby"); + String replaceAll = m.replaceAll("Ruby"); + System.out.println("Matcher.replaceFirst: " + replaceFirst); + System.out.println("Matcher.replaceAll: " + replaceAll); + } + + public static void Regex_Matcher_appendReplacement_appendTail() { + String content = "Java, Python, Go"; + Pattern p = Pattern.compile(","); + Matcher m = p.matcher(content); + StringBuffer sb = new StringBuffer(); + while (m.find()) { + m.appendReplacement(sb, ":"); + } + m.appendTail(sb); + System.out.println(sb.toString()); + } + + + public static void main(String[] args) { + Regex_Pattern_matches(); + Regex_Matcher_group(); + Regex_Matcher_start_end(); + Regex_Matcher_lookingAt(); + Regex_Matcher_replaceFirst_replaceAll(); + Regex_Matcher_appendReplacement_appendTail(); + } +} From 2fb275d80562bae68b4dcfb90d4e2812631b4b41 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Wed, 28 Jun 2017 15:12:30 +0800 Subject: [PATCH 11/41] Method --- src/tutorial/Methods.java | 62 ++++++++++++++++++++++++++++++ src/tutorial/Regexes.java | 79 +++++++++++++++++++-------------------- 2 files changed, 101 insertions(+), 40 deletions(-) create mode 100644 src/tutorial/Methods.java diff --git a/src/tutorial/Methods.java b/src/tutorial/Methods.java new file mode 100644 index 0000000..559ec1f --- /dev/null +++ b/src/tutorial/Methods.java @@ -0,0 +1,62 @@ +/** + * Created by Oliver on 28/06/2017. + */ +public class Methods { + public static void swap(int i, int j) { + System.out.printf("Before swap: i=%d, j=%d%n", i, j); + int tmp = i; + i = j; + j = tmp; + System.out.printf("After swap: i=%d, j=%d%n", i, j); + } + + public static float max(float i, float j) { + return Math.max(i, j); + } + + public static void printMax(double... x) { + if (x.length == 0) { + System.out.println("No argument..."); + return; + } + double result = x[0]; + for (int i = 0; i < x.length; i++) { + if (x[i] > result) { + result = x[i]; + } + } + System.out.printf("PrintMax: " + result); + } + + public static void Method_swap() { + int x = 10; + int y = 20; + swap(x, y); + System.out.printf("x=%d, y=%d%n", x, y); // 方法被调用后,实参的值并没有改变 + } + + public static void Method_max() { + float f = max(8.0f, 9.1f); + System.out.printf("Max float: %f%n", f); + } + + public static void Method_printMax() { + printMax(); + printMax(9.12, 10.34, 1.34, 3.13); + } + + // finalize( )在对象被垃圾收集器析构(回收)之前调用,它用来清除回收对象 + protected void finalize() throws Throwable { + super.finalize(); + System.out.println("Everything is disposed."); + } + + public static void main(String[] args) { + Method_swap(); + Method_max(); + Method_printMax(); + + System.gc(); //调用Java垃圾收集器 + + } +} diff --git a/src/tutorial/Regexes.java b/src/tutorial/Regexes.java index 911949a..5ce6d44 100644 --- a/src/tutorial/Regexes.java +++ b/src/tutorial/Regexes.java @@ -6,46 +6,45 @@ */ public class Regexes { /* 正则表达式语法: - \ 将下一字符标记为特殊字符、文本、反向引用或八进制转义符。例如,"n"匹配字符"n"。"\n"匹配换行符。序列"\\"匹配"\","\("匹配"("。 - ^ 匹配输入字符串开始的位置。如果设置了 RegExp 对象的 Multiline 属性,^ 还会与"\n"或"\r"之后的位置匹配。 - $ 匹配输入字符串结尾的位置。如果设置了 RegExp 对象的 Multiline 属性,$ 还会与"\n"或"\r"之前的位置匹配。 - * 零次或多次匹配前面的字符或子表达式。例如,zo* 匹配"z"和"zoo"。* 等效于 {0,}。 - + 一次或多次匹配前面的字符或子表达式。例如,"zo+"与"zo"和"zoo"匹配,但与"z"不匹配。+ 等效于 {1,}。 - ? 零次或一次匹配前面的字符或子表达式。例如,"do(es)?"匹配"do"或"does"中的"do"。? 等效于 {0,1}。 - {n} n 是非负整数。正好匹配 n 次。例如,"o{2}"与"Bob"中的"o"不匹配,但与"food"中的两个"o"匹配。 - {n,} n 是非负整数。至少匹配 n 次。例如,"o{2,}"不匹配"Bob"中的"o",而匹配"foooood"中的所有 o。"o{1,}"等效于"o+"。"o{0,}"等效于"o*"。 - {n,m} M 和 n 是非负整数,其中 n <= m。匹配至少 n 次,至多 m 次。例如,"o{1,3}"匹配"fooooood"中的头三个 o。'o{0,1}' 等效于 'o?'。注意:您不能将空格插入逗号和数字之间。 - ? 当此字符紧随任何其他限定符(*、+、?、{n}、{n,}、{n,m})之后时,匹配模式是"非贪心的"。"非贪心的"模式匹配搜索到的、尽可能短的字符串,而默认的"贪心的"模式匹配搜索到的、尽可能长的字符串。例如,在字符串"oooo"中,"o+?"只匹配单个"o",而"o+"匹配所有"o"。 - . 匹配除"\r\n"之外的任何单个字符。若要匹配包括"\r\n"在内的任意字符,请使用诸如"[\s\S]"之类的模式。 - (pattern) 匹配 pattern 并捕获该匹配的子表达式。可以使用 $0…$9 属性从结果"匹配"集合中检索捕获的匹配。若要匹配括号字符 ( ),请使用"\("或者"\)"。 - (?:pattern) 匹配 pattern 但不捕获该匹配的子表达式,即它是一个非捕获匹配,不存储供以后使用的匹配。这对于用"or"字符 (|) 组合模式部件的情况很有用。例如,'industr(?:y|ies) 是比 'industry|industries' 更经济的表达式。 - (?=pattern) 执行正向预测先行搜索的子表达式,该表达式匹配处于匹配 pattern 的字符串的起始点的字符串。它是一个非捕获匹配,即不能捕获供以后使用的匹配。例如,'Windows (?=95|98|NT|2000)' 匹配"Windows 2000"中的"Windows",但不匹配"Windows 3.1"中的"Windows"。预测先行不占用字符,即发生匹配后,下一匹配的搜索紧随上一匹配之后,而不是在组成预测先行的字符后。 - (?!pattern) 执行反向预测先行搜索的子表达式,该表达式匹配不处于匹配 pattern 的字符串的起始点的搜索字符串。它是一个非捕获匹配,即不能捕获供以后使用的匹配。例如,'Windows (?!95|98|NT|2000)' 匹配"Windows 3.1"中的 "Windows",但不匹配"Windows 2000"中的"Windows"。预测先行不占用字符,即发生匹配后,下一匹配的搜索紧随上一匹配之后,而不是在组成预测先行的字符后。 - x|y 匹配 x 或 y。例如,'z|food' 匹配"z"或"food"。'(z|f)ood' 匹配"zood"或"food"。 - [xyz] 字符集。匹配包含的任一字符。例如,"[abc]"匹配"plain"中的"a"。 - [^xyz] 反向字符集。匹配未包含的任何字符。例如,"[^abc]"匹配"plain"中"p","l","i","n"。 - [a-z] 字符范围。匹配指定范围内的任何字符。例如,"[a-z]"匹配"a"到"z"范围内的任何小写字母。 - [^a-z] 反向范围字符。匹配不在指定的范围内的任何字符。例如,"[^a-z]"匹配任何不在"a"到"z"范围内的任何字符。 - \b 匹配一个字边界,即字与空格间的位置。例如,"er\b"匹配"never"中的"er",但不匹配"verb"中的"er"。 - \B 非字边界匹配。"er\B"匹配"verb"中的"er",但不匹配"never"中的"er"。 - \cx 匹配 x 指示的控制字符。例如,\cM 匹配 Control-M 或回车符。x 的值必须在 A-Z 或 a-z 之间。如果不是这样,则假定 c 就是"c"字符本身。 - \d 数字字符匹配。等效于 [0-9]。 - \D 非数字字符匹配。等效于 [^0-9]。 - \f 换页符匹配。等效于 \x0c 和 \cL。 - \n 换行符匹配。等效于 \x0a 和 \cJ。 - \r 匹配一个回车符。等效于 \x0d 和 \cM。 - \s 匹配任何空白字符,包括空格、制表符、换页符等。与 [ \f\n\r\t\v] 等效。 - \S 匹配任何非空白字符。与 [^ \f\n\r\t\v] 等效。 - \t 制表符匹配。与 \x09 和 \cI 等效。 - \v 垂直制表符匹配。与 \x0b 和 \cK 等效。 - \w 匹配任何字类字符,包括下划线。与"[A-Za-z0-9_]"等效。 - \W 与任何非单词字符匹配。与"[^A-Za-z0-9_]"等效。 - \xn 匹配 n,此处的 n 是一个十六进制转义码。十六进制转义码必须正好是两位数长。例如,"\x41"匹配"A"。"\x041"与"\x04"&"1"等效。允许在正则表达式中使用 ASCII 代码。 - \num 匹配 num,此处的 num 是一个正整数。到捕获匹配的反向引用。例如,"(.)\1"匹配两个连续的相同字符。 - \n 标识一个八进制转义码或反向引用。如果 \n 前面至少有 n 个捕获子表达式,那么 n 是反向引用。否则,如果 n 是八进制数 (0-7),那么 n 是八进制转义码。 - \nm 标识一个八进制转义码或反向引用。如果 \nm 前面至少有 nm 个捕获子表达式,那么 nm 是反向引用。如果 \nm 前面至少有 n 个捕获,则 n 是反向引用,后面跟有字符 m。如果两种前面的情况都不存在,则 \nm 匹配八进制值 nm,其中 n 和 m 是八进制数字 (0-7)。 - \nml 当 n 是八进制数 (0-3),m 和 l 是八进制数 (0-7) 时,匹配八进制转义码 nml。 - \un 匹配 n,其中 n 是以四位十六进制数表示的 Unicode 字符。例如,\u00A9 匹配版权符号 (©)。 + \ 将下一字符标记为特殊字符、文本、反向引用或八进制转义符。例如,"n"匹配字符"n"。"\n"匹配换行符。序列"\\"匹配"\","\("匹配"("。 + ^ 匹配输入字符串开始的位置。如果设置了 RegExp 对象的 Multiline 属性,^ 还会与"\n"或"\r"之后的位置匹配。 + $ 匹配输入字符串结尾的位置。如果设置了 RegExp 对象的 Multiline 属性,$ 还会与"\n"或"\r"之前的位置匹配。 + * 零次或多次匹配前面的字符或子表达式。例如,zo* 匹配"z"和"zoo"。* 等效于 {0,}。 + + 一次或多次匹配前面的字符或子表达式。例如,"zo+"与"zo"和"zoo"匹配,但与"z"不匹配。+ 等效于 {1,}。 + ? 零次或一次匹配前面的字符或子表达式。例如,"do(es)?"匹配"do"或"does"中的"do"。? 等效于 {0,1}。 + {n} n 是非负整数。正好匹配 n 次。例如,"o{2}"与"Bob"中的"o"不匹配,但与"food"中的两个"o"匹配。 + {n,} n 是非负整数。至少匹配 n 次。例如,"o{2,}"不匹配"Bob"中的"o",而匹配"foooood"中的所有 o。"o{1,}"等效于"o+"。"o{0,}"等效于"o*"。 + {n,m} M 和 n 是非负整数,其中 n <= m。匹配至少 n 次,至多 m 次。例如,"o{1,3}"匹配"fooooood"中的头三个 o。'o{0,1}' 等效于 'o?'。注意:您不能将空格插入逗号和数字之间。 + ? 当此字符紧随任何其他限定符(*、+、?、{n}、{n,}、{n,m})之后时,匹配模式是"非贪心的"。"非贪心的"模式匹配搜索到的、尽可能短的字符串,而默认的"贪心的"模式匹配搜索到的、尽可能长的字符串。例如,在字符串"oooo"中,"o+?"只匹配单个"o",而"o+"匹配所有"o"。 + . 匹配除"\r\n"之外的任何单个字符。若要匹配包括"\r\n"在内的任意字符,请使用诸如"[\s\S]"之类的模式。 + (pattern) 匹配 pattern 并捕获该匹配的子表达式。可以使用 $0…$9 属性从结果"匹配"集合中检索捕获的匹配。若要匹配括号字符 ( ),请使用"\("或者"\)"。 + (?:pattern) 匹配 pattern 但不捕获该匹配的子表达式,即它是一个非捕获匹配,不存储供以后使用的匹配。这对于用"or"字符 (|) 组合模式部件的情况很有用。例如,'industr(?:y|ies) 是比 'industry|industries' 更经济的表达式。 + (?=pattern) 执行正向预测先行搜索的子表达式,该表达式匹配处于匹配 pattern 的字符串的起始点的字符串。它是一个非捕获匹配,即不能捕获供以后使用的匹配。例如,'Windows (?=95|98|NT|2000)' 匹配"Windows 2000"中的"Windows",但不匹配"Windows 3.1"中的"Windows"。预测先行不占用字符,即发生匹配后,下一匹配的搜索紧随上一匹配之后,而不是在组成预测先行的字符后。 + (?!pattern) 执行反向预测先行搜索的子表达式,该表达式匹配不处于匹配 pattern 的字符串的起始点的搜索字符串。它是一个非捕获匹配,即不能捕获供以后使用的匹配。例如,'Windows (?!95|98|NT|2000)' 匹配"Windows 3.1"中的 "Windows",但不匹配"Windows 2000"中的"Windows"。预测先行不占用字符,即发生匹配后,下一匹配的搜索紧随上一匹配之后,而不是在组成预测先行的字符后。 + x|y 匹配 x 或 y。例如,'z|food' 匹配"z"或"food"。'(z|f)ood' 匹配"zood"或"food"。 + [xyz] 字符集。匹配包含的任一字符。例如,"[abc]"匹配"plain"中的"a"。 + [^xyz] 反向字符集。匹配未包含的任何字符。例如,"[^abc]"匹配"plain"中"p","l","i","n"。 + [a-z] 字符范围。匹配指定范围内的任何字符。例如,"[a-z]"匹配"a"到"z"范围内的任何小写字母。 + [^a-z] 反向范围字符。匹配不在指定的范围内的任何字符。例如,"[^a-z]"匹配任何不在"a"到"z"范围内的任何字符。 + \b 匹配一个字边界,即字与空格间的位置。例如,"er\b"匹配"never"中的"er",但不匹配"verb"中的"er"。 + \B 非字边界匹配。"er\B"匹配"verb"中的"er",但不匹配"never"中的"er"。 + \cx 匹配 x 指示的控制字符。例如,\cM 匹配 Control-M 或回车符。x 的值必须在 A-Z 或 a-z 之间。如果不是这样,则假定 c 就是"c"字符本身。 + \d 数字字符匹配。等效于 [0-9]。 + \D 非数字字符匹配。等效于 [^0-9]。 + \f 换页符匹配。等效于 \x0c 和 \cL。 + \n 换行符匹配。等效于 \x0a 和 \cJ。 + \r 匹配一个回车符。等效于 \x0d 和 \cM。 + \s 匹配任何空白字符,包括空格、制表符、换页符等。与 [ \f\n\r\t\v] 等效。 + \S 匹配任何非空白字符。与 [^ \f\n\r\t\v] 等效。 + \t 制表符匹配。与 \x09 和 \cI 等效。 + \v 垂直制表符匹配。与 \x0b 和 \cK 等效。 + \w 匹配任何字类字符,包括下划线。与"[A-Za-z0-9_]"等效。 + \W 与任何非单词字符匹配。与"[^A-Za-z0-9_]"等效。 + \xn 匹配 n,此处的 n 是一个十六进制转义码。十六进制转义码必须正好是两位数长。例如,"\x41"匹配"A"。"\x041"与"\x04"&"1"等效。允许在正则表达式中使用 ASCII 代码。 + \num 匹配 num,此处的 num 是一个正整数。到捕获匹配的反向引用。例如,"(.)\1"匹配两个连续的相同字符。 + \n 标识一个八进制转义码或反向引用。如果 \n 前面至少有 n 个捕获子表达式,那么 n 是反向引用。否则,如果 n 是八进制数 (0-7),那么 n 是八进制转义码。 + \nm 标识一个八进制转义码或反向引用。如果 \nm 前面至少有 nm 个捕获子表达式,那么 nm 是反向引用。如果 \nm 前面至少有 n 个捕获,则 n 是反向引用,后面跟有字符 m。如果两种前面的情况都不存在,则 \nm 匹配八进制值 nm,其中 n 和 m 是八进制数字 (0-7)。 + \nml 当 n 是八进制数 (0-3),m 和 l 是八进制数 (0-7) 时,匹配八进制转义码 nml */ public static void Regex_Pattern_matches() { From f9efa29d37dec3b0231355cf705d81cec4a72bd9 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Wed, 28 Jun 2017 16:01:57 +0800 Subject: [PATCH 12/41] IO --- src/tutorial/IO.java | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/tutorial/IO.java diff --git a/src/tutorial/IO.java b/src/tutorial/IO.java new file mode 100644 index 0000000..36bb235 --- /dev/null +++ b/src/tutorial/IO.java @@ -0,0 +1,42 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * Created by Oliver on 28/06/2017. + */ +public class IO { + public static void IO_BufferedReader() throws IOException { + // 把 System.in 包装在一个 BufferedReader 对象中来创建一个字符流 + char c; + String s; + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Input character, 'q' to exit"); + // 使用 BufferedReader 在控制台读取字符 + do { + c = (char) reader.read(); + System.out.println(c); + } while (c != 'q'); + + System.out.println("Enter lines of text."); + System.out.println("Enter 'end' to quit."); + do { + s = reader.readLine(); + System.out.println(s); + } while (!s.equals("end")); + } + + public static void IO_write() { + int b; + b = 'A'; + // write() 方法不经常使用,因为 print() 和 println() 方法用起来更为方便 + System.out.write(b); + System.out.write('\n'); + + } + + public static void main(String[] args) throws IOException { + IO_BufferedReader(); + IO_write(); + } +} From d53359018ef32bc6a25e4cfdf29d69a90fda4e2b Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Wed, 28 Jun 2017 17:41:35 +0800 Subject: [PATCH 13/41] File --- src/tutorial/Files.java | 76 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/tutorial/Files.java diff --git a/src/tutorial/Files.java b/src/tutorial/Files.java new file mode 100644 index 0000000..5ec3ea0 --- /dev/null +++ b/src/tutorial/Files.java @@ -0,0 +1,76 @@ +import java.io.*; + +/** + * Created by Oliver on 28/06/2017. + */ +public class Files { + public static void Files_FileOutputStream() throws IOException { + String filePath = System.getProperty("user.dir") + File.separator + "failCount.properties"; + + FileOutputStream fos = new FileOutputStream(filePath); // 构建FileOutputStream对象,文件不存在会自动新建 + // 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk + OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8"); + + char[] forWrite = {'中', '文', '输', '入'}; + for (int i = 0; i < forWrite.length; i++) { + writer.append(forWrite[i]); // writes the bytes + } + writer.close(); //关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉 + fos.close(); // 关闭输出流,释放系统资源 + } + + public static void Files_FileInputStream() throws IOException { + String filePath = System.getProperty("user.dir") + File.separator + "failCount.properties"; + + FileInputStream fis = new FileInputStream(filePath); // 构建FileInputStream对象 + // 构建InputStreamReader对象,编码与写入相同 + InputStreamReader reader = new InputStreamReader(fis, "UTF-8"); + + StringBuffer buffer = new StringBuffer(); + while (reader.ready()) { + buffer.append((char) reader.read()); // 转成char加到StringBuffer对象中 + } + System.out.printf("FileInputStream.read(): %d%n", fis.read()); + System.out.println("StringBuffer append char from InputStreamReader: " + buffer.toString()); + reader.close(); // 关闭读取流 + fis.close(); // 关闭输入流,释放系统资源 + } + + public static void Files_mkdirs() { + String filePath = System.getProperty("user.dir") + File.separator + "/tmp/tmp"; + File f = new File(filePath); + System.out.println("mkdir: " + f.mkdir()); + System.out.println("mkdirs: " + f.mkdirs()); // mkdirs()方法创建一个文件夹和它的所有父文件夹 + } + + public static void Files_list() { + String filePath = System.getProperty("user.dir") + File.separator + "src/tutorial"; + File f = new File(filePath); + if (f.isDirectory()) { + System.out.println("目录: " + f.getName()); + for (String fileName : f.list()) { + File file = new File(filePath + "/" + fileName); + if (!file.isDirectory()) { + System.out.println("文件: " + file.getName()); + } else { + System.out.println("目录: " + file.getName()); + } + } + } + } + + public static void Files_delete() { + String filePath = System.getProperty("user.dir") + File.separator + "/tmp/tmp"; + File file = new File(filePath); + System.out.println("File.delete(): " + file.delete()); + } + + public static void main(String[] args) throws IOException { + System.out.println(System.getProperties()); + Files_FileOutputStream(); + Files_FileInputStream(); + Files_mkdirs(); + Files_list(); + Files_delete(); + } +} From ec0a105b773048829c1c75c5037e90c44fc7f4cd Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Wed, 28 Jun 2017 18:53:30 +0800 Subject: [PATCH 14/41] Scanner --- src/tutorial/Scanners.java | 88 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 src/tutorial/Scanners.java diff --git a/src/tutorial/Scanners.java b/src/tutorial/Scanners.java new file mode 100644 index 0000000..e47db68 --- /dev/null +++ b/src/tutorial/Scanners.java @@ -0,0 +1,88 @@ +import java.util.Scanner; + +/** + * Created by Oliver on 28/06/2017. + */ +public class Scanners { + /* + next(): + 1、一定要读取到有效字符后才可以结束输入。 + 2、对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。 + 3、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。 + next() 不能得到带有空格的字符串。 + */ + public static void Scanner_next() { + Scanner scanner = new Scanner(System.in); + System.out.println("Scanner.next方式接收数据: "); + do { + String next = scanner.next(); + if (next.equals("q")) { + return; + } + System.out.println("Scanner.next(): " + next); + } while (scanner.hasNext()); + } + + /* + 1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。 + 2、可以获得空白。 + */ + public static void Scanner_nextLine() { + Scanner scanner = new Scanner(System.in); + System.out.println("Scanner.nextLine方式接收数据: "); + do { + String line = scanner.nextLine(); + System.out.println("Scanner.nextLine(): " + line); + if (line.equals("q")) { + return; + } + } while (scanner.hasNextLine()); + } + + public static void sum() { + Scanner scanner = new Scanner(System.in); + int sum = 0; + System.out.println("Input int number for sum: "); + do { + String s = scanner.next(); + if (s.equals("q")) { + return; + } else { + int input = Integer.parseInt(s); + sum += input; + System.out.println("Input: " + input); + System.out.println("Now the sum is: " + sum); + } + + } while (scanner.hasNext()); + } + + public static void average() { + Scanner scanner = new Scanner(System.in); + double sum = 0d; + double average; + int count = 0; + System.out.println("Input double number for average: "); + do { + String s = scanner.next(); + if (s.equals("q")) { + return; + } else { + count++; + double input = Double.parseDouble(s); + sum += input; + average = sum / count; + System.out.println("Sum: " + sum); + System.out.println("Average: " + average); + } + } while (scanner.hasNext()); + } + + + public static void main(String[] args) { + Scanner_next(); + Scanner_nextLine(); + sum(); + average(); + } +} From f5337c1cb7fc195135e22030f4ade2062822bf41 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Thu, 29 Jun 2017 10:36:07 +0800 Subject: [PATCH 15/41] Exception --- failCount.properties | 35 +------------- src/tutorial/Exceptions.java | 93 ++++++++++++++++++++++++++++++++++++ src/tutorial/Files.java | 6 +-- 3 files changed, 97 insertions(+), 37 deletions(-) create mode 100644 src/tutorial/Exceptions.java diff --git a/failCount.properties b/failCount.properties index 67a0aaf..e791b5b 100644 --- a/failCount.properties +++ b/failCount.properties @@ -1,34 +1 @@ -# -#Mon Apr 17 18:22:26 CST 2017 -uploadWithFileConvert=0 -registerVipJr=0 -loginVipjr=0 -getAfterQuestion=0 -reviewPage=1 -getClientReservedLessons=1 -getClientClasses=0 -lessonInfo=1 -setReservation=0 -newLogin=0 -getClientLessonHistory=0 -getList=0 -getJRHotNewsList=0 -lessonQuestions=1 -getLevelInfo=0 -setAfterQuestionEvaluation=0 -homeLogin=0 -getClientBasicInfoByEmail=0 -activateAccount=0 -preparePage=1 -reservationInformation=0 -getClientClassRecordTimeList=1 -beforeTest=2 -getJRNewsDetailByNewsID=0 -afterTest=0 -checkRegisterMail=0 -getDCGS=0 -lessonVocab=1 -classContract=0 -data=0 -viewMyVideo=0 -recommandList=0 +中文输入 \ No newline at end of file diff --git a/src/tutorial/Exceptions.java b/src/tutorial/Exceptions.java new file mode 100644 index 0000000..9fc25a3 --- /dev/null +++ b/src/tutorial/Exceptions.java @@ -0,0 +1,93 @@ +import java.io.*; +import java.rmi.RemoteException; + +/** + * Created by Oliver on 28/06/2017. + */ +public class Exceptions { + public static void Exception_Single_catch() { + int[] num = new int[2]; + try { + System.out.println(num[5]); + } catch (IndexOutOfBoundsException e) { + System.out.println(e); + } + } + + public static void Exception_Multi_catch() { + String path = System.getProperty("user.dir") + File.separator + "failCount.properties"; + + try { + FileInputStream fis = new FileInputStream(path); + InputStreamReader reader = new InputStreamReader(fis, "UTF-8"); + int x = reader.read(); + System.out.println(x); + } catch (FileNotFoundException f) { + f.printStackTrace(); + } catch (IOException i) { + i.printStackTrace(); + } + } + + public static void Exception_throw() { + try { + throw new RemoteException(); + } catch (RemoteException r) { + System.out.println("RemoteException happened: "); + r.printStackTrace(); + } + } + + public static void Exception_finally() { + int[] nums = new int[2]; + try { + System.out.println(nums[5]); + } catch (IndexOutOfBoundsException e) { + System.out.println("IndexOutOfBoundsException->> " + e); + } finally { + System.out.println("Finally block is executed."); + } + } + + static double balance = 100; + + public static void withdraw(double amount) throws InsufficientFundsException { + if (amount <= balance) { + balance -= amount; + } else { + double deficiency = amount - balance; + throw new InsufficientFundsException(deficiency); + } + } + + public static void Exception_InsufficientFundsException() { + try { + withdraw(500); + } catch (InsufficientFundsException e) { + System.out.println("Sorry, but you are short $" + + e.getDeficiency()); + e.printStackTrace(); + } + } + + + public static void main(String[] args) { + Exception_Single_catch(); + Exception_Multi_catch(); + Exception_throw(); + Exception_finally(); + Exception_InsufficientFundsException(); + } +} + +class InsufficientFundsException extends Exception { + private double deficiency; + + public InsufficientFundsException(double deficiency) { + this.deficiency = deficiency; + } + + public double getDeficiency() { + return deficiency; + } +} diff --git a/src/tutorial/Files.java b/src/tutorial/Files.java index 5ec3ea0..43cdc90 100644 --- a/src/tutorial/Files.java +++ b/src/tutorial/Files.java @@ -11,9 +11,9 @@ public static void Files_FileOutputStream() throws IOException { // 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8"); - char[] forWrite = {'中', '文', '输', '入'}; - for (int i = 0; i < forWrite.length; i++) { - writer.append(forWrite[i]); // writes the bytes + char[] content = {'中', '文', '输', '入'}; + for (int i = 0; i < content.length; i++) { + writer.append(content[i]); // writes the bytes } writer.close(); //关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉 fos.close(); // 关闭输出流,释放系统资源 From 7023f08b78fde2f183be0cea72b6c79da81917ab Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Thu, 29 Jun 2017 14:23:27 +0800 Subject: [PATCH 16/41] Extends --- src/tutorial/Extends.java | 84 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 src/tutorial/Extends.java diff --git a/src/tutorial/Extends.java b/src/tutorial/Extends.java new file mode 100644 index 0000000..cd7d980 --- /dev/null +++ b/src/tutorial/Extends.java @@ -0,0 +1,84 @@ +/** + * Created by Oliver on 29/06/2017. + */ +public class Extends { + public static void main(String[] args) { + Penguin pen = new Penguin(); + Penguin penguin = new Penguin("James", 7); + penguin.introduction(); + + SubClass subClass1 = new SubClass(); + SubClass subClass2 = new SubClass(100); + + } +} + + +class Animals { + private String name; + private int id; + + Animals() { + System.out.println("Super constructor without args"); + } + + Animals(String myName, int myId) { + name = myName; + id = myId; + } + + public void eat() { + System.out.println(name + "正在吃"); + } + + public void sleep() { + System.out.println(name + "正在睡"); + } + + public void introduction() { + System.out.println("大家好!我是" + id + "号" + name + "."); + } +} + + +class Penguin extends Animals { + // 如果父类有无参构造器,则在子类的构造器中用super调用父类构造器不是必须的,如果没有使用super关键字,系统会自动调用父类的无参构造器。 + Penguin() { + // super(); + } + // 父类的构造器带有参数的,则必须在子类的构造器中显式地通过super关键字调用父类的构造器并配以适当的参数列表 + Penguin(String name, int id) { + super(name, id); + } + + public void introduction() { + super.introduction(); + } +} + +class SuperClass { + int n = 1; + + public SuperClass(){ + System.out.println("SuperClass constructor without args"); + } + + public SuperClass(int n) { + System.out.println("SuperClass constructor with args: " + n); + this.n = n; + } +} + +class SubClass extends SuperClass { + public SubClass() { + super(300); + System.out.println("SubClass constructor without args"); + } + + public SubClass(int n) { + // super(); // 如果父类有无参构造器,则在子类的构造器中用super调用父类构造器不是必须的,如果没有使用super关键字,系统会自动调用父类的无参构造器。 + this(); // 调用当前类的构造方法 + System.out.println("SubClass constructor with args: " + n); + + } +} \ No newline at end of file From 1f7ba2ed9beb2fbdc597e36a2d061c9766a064af Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Thu, 29 Jun 2017 15:18:14 +0800 Subject: [PATCH 17/41] Override, Overload --- src/tutorial/Extends.java | 3 +- src/tutorial/OverrideOverload.java | 64 ++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 src/tutorial/OverrideOverload.java diff --git a/src/tutorial/Extends.java b/src/tutorial/Extends.java index cd7d980..9b6519b 100644 --- a/src/tutorial/Extends.java +++ b/src/tutorial/Extends.java @@ -46,6 +46,7 @@ class Penguin extends Animals { Penguin() { // super(); } + // 父类的构造器带有参数的,则必须在子类的构造器中显式地通过super关键字调用父类的构造器并配以适当的参数列表 Penguin(String name, int id) { super(name, id); @@ -59,7 +60,7 @@ public void introduction() { class SuperClass { int n = 1; - public SuperClass(){ + public SuperClass() { System.out.println("SuperClass constructor without args"); } diff --git a/src/tutorial/OverrideOverload.java b/src/tutorial/OverrideOverload.java new file mode 100644 index 0000000..ee1301b --- /dev/null +++ b/src/tutorial/OverrideOverload.java @@ -0,0 +1,64 @@ +/** + * Created by Oliver on 29/06/2017. + */ +public class OverrideOverload { + /* + 方法的重写(Overriding)和重载(Overloading)是java多态性的不同表现, + 重写是父类与子类之间多态性的一种表现,重载可以理解成多态的具体表现形式。 + */ + public static void main(String[] args) { + Animal animal = new Animal(); + Dog dog = new Dog(); + animal.move(); + dog.move(); + dog.bark(); + dog.bark("woof!"); + } + +} + +class Animal { + /* 子类和父类在同一个包中,那么子类可以重写父类所有方法,除了声明为private和final的方法。 + 子类和父类不在同一个包中,那么子类只能够重写父类的声明为public和protected的非final方法。 + */ + public void move() { + System.out.println("Animal.move()"); + } +} + +class Dog extends Animal { + /* 重写(override)规则 + 参数列表必须完全与被重写方法的相同; + 返回类型必须完全与被重写方法的返回类型相同; + 访问权限不能比父类中被重写的方法的访问权限更低。例如:如果父类的一个方法被声明为public,那么在子类中重写该方法就不能声明为protected。 + 父类的成员方法只能被它的子类重写。 + 声明为final的方法不能被重写。 + 声明为static的方法不能被重写,但是能够被再次声明。 + 子类和父类在同一个包中,那么子类可以重写父类所有方法,除了声明为private和final的方法。 + 子类和父类不在同一个包中,那么子类只能够重写父类的声明为public和protected的非final方法。 + 重写的方法能够抛出任何非强制异常,无论被重写的方法是否抛出异常。但是,重写的方法不能抛出新的强制性异常,或者比被重写方法声明的更广泛的强制性异常,反之则可以。 + 构造方法不能被重写。 + 如果不能继承一个方法,则不能重写这个方法。 + */ + public void move() { + super.move(); + System.out.println("Dog.move()"); + } + + public void bark() { + System.out.println("Dog.bark()"); + } + + /* 重载(overloading)规则 + 被重载的方法必须改变参数列表(参数个数或类型或顺序不一样); + 被重载的方法可以改变返回类型; + 被重载的方法可以改变访问修饰符; + 被重载的方法可以声明新的或更广的检查异常; + 方法能够在同一个类中或者在一个子类中被重载。 + 无法以返回值类型作为重载函数的区分标准。 + */ + public void bark(String s) { + System.out.println(s); + } + +} \ No newline at end of file From e6ec5a2b1f399809b20ddb709249c7800265b2e8 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Thu, 29 Jun 2017 18:03:14 +0800 Subject: [PATCH 18/41] Abstract --- src/tutorial/Abstracts.java | 96 +++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 src/tutorial/Abstracts.java diff --git a/src/tutorial/Abstracts.java b/src/tutorial/Abstracts.java new file mode 100644 index 0000000..561d275 --- /dev/null +++ b/src/tutorial/Abstracts.java @@ -0,0 +1,96 @@ +/** + * Created by Oliver on 29/06/2017. + */ +public class Abstracts { + public static void main(String[] args) { + Salary s = new Salary("James Salary", "Shanghai", 7, 20000); + AbstractEmployee e = new Salary("John Employee", "Tokyo", 9, 30000); + + System.out.println("Call mailCheck using Salary reference --"); + s.mailCheck(); + + System.out.println("\nCall mailCheck using Employee reference --"); + e.mailCheck(); + } + +} + + +class Salary extends AbstractEmployee { + private double salary; + + public Salary(String name, String address, int number, double salary) { + super(name, address, number); + setSalary(salary); + } + + public void setSalary(double salary) { + if (salary >= 0) { + this.salary = salary; + } + } + + public double getSalary() { + return this.salary; + } + + // 任何子类必须重写父类的抽象方法,或者声明自身为抽象类 + public double computePay() { + System.out.println("Inside Salary computePay"); + return this.salary; + } + + public void mailCheck() { + System.out.println("Within mailCheck of Salary class "); + System.out.println("Mailing a check to " + getName() + + " " + getAddress()); + } +} + +/* 抽象类总结 +1. 抽象类不能被实例化,如果被实例化,就会报错,编译无法通过。只有抽象类的非抽象子类可以创建对象。 +2. 抽象类中不一定包含抽象方法,但是有抽象方法的类必定是抽象类。 +3. 抽象类中的抽象方法只是声明,不包含方法体,就是不给出方法的具体实现也就是方法的具体功能。 +4. 构造方法,类方法(用static修饰的方法)不能声明为抽象方法。 +5. 抽象类的子类必须给出抽象类中的抽象方法的具体实现,除非该子类也是抽象类。 +*/ +abstract class AbstractEmployee { + private String name; + private String address; + private int number; + + public AbstractEmployee(String name, String address, int number) { + System.out.println("Constructing an Employee"); + this.name = name; + this.address = address; + this.number = number; + } + + // 抽象方法只能在抽象类 + public abstract double computePay(); + + public void mailCheck() { + System.out.println("Mailing a check to " + this.name + + " " + this.address); + } + + public String toString() { + return name + " " + address + " " + number; + } + + public String getName() { + return name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String newAddress) { + address = newAddress; + } + + public int getNumber() { + return number; + } +} \ No newline at end of file From dbb9725d1575b819b29ebb3bb51c6874a3c4ab6f Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Thu, 29 Jun 2017 18:33:24 +0800 Subject: [PATCH 19/41] Encapsulation --- src/tutorial/Encapsulations.java | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/tutorial/Encapsulations.java diff --git a/src/tutorial/Encapsulations.java b/src/tutorial/Encapsulations.java new file mode 100644 index 0000000..1141405 --- /dev/null +++ b/src/tutorial/Encapsulations.java @@ -0,0 +1,37 @@ +/** + * Created by Oliver on 29/06/2017. + */ +public class Encapsulations { + public static void main(String[] args) { + Person person = new Person(); + person.setAge(20); + person.setName("Alice"); + System.out.printf("I am %s and %d years old.", person.getName(), person.getAge()); + } +} + +class Person { + /* 将 name 和 age 属性设置为私有的,只能本类才能访问,其他类都访问不了,如此就对信息进行了隐藏。 + */ + private String name; + private int age; + + /* 公共方法访问,也就是创建一对赋取值方法,用于对私有属性的访问 + public方法是外部类访问该类成员变量的入口 + */ + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public void setAge(int age) { + this.age = age; + } + + public int getAge() { + return age; + } +} From 769e08b2b5913b7126dd72906a67e5da47d35151 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Fri, 30 Jun 2017 10:45:50 +0800 Subject: [PATCH 20/41] Interface --- src/tutorial/Interfaces.java | 72 ++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/tutorial/Interfaces.java diff --git a/src/tutorial/Interfaces.java b/src/tutorial/Interfaces.java new file mode 100644 index 0000000..eb07d97 --- /dev/null +++ b/src/tutorial/Interfaces.java @@ -0,0 +1,72 @@ +/** + * Created by Oliver on 30/06/2017. + */ +public class Interfaces { + public static void main(String[] args) { + MammalInt m = new MammalInt(); + m.eat(); + m.travel(); + } + +} + +interface AnimalInterface { + /*接口是隐式抽象的,当声明一个接口的时候,不必使用abstract关键字。 + 接口中每一个方法也是隐式抽象的,声明时同样不需要abstract关键子。 + 接口中的方法都是公有的。 + */ + void eat(); + + void travel(); + +} + +interface Sports { + void setHomeTeam(String name); + + void setVisitingTeam(String name); +} + +/* 实现Football接口的类需要实现五个方法,其中两个来自于Sports接口 */ +interface Football extends Sports { + void homeTeamScored(int points); + + void visitingTeamScored(int points); + + void endOfQuarter(int quarter); +} + +/* Hockey接口自己声明了四个方法,从Sports接口继承了两个方法,这样,实现Hockey接口的类需要实现六个方法 */ +interface Hockey extends Sports { + void homeGoalScored(); + + void visitingGoalScored(); + + void endOfPeriod(int period); + + void overtimePeriod(int ot); +} + +/* 标记接口主要用于以下两种目的: +1. 建立一个公共的父接口: +正如EventListener接口,这是由几十个其他接口扩展的Java API,你可以使用一个标记接口来建立一组接口的父接口。 +例如:当一个接口继承了EventListener接口,Java虚拟机(JVM)就知道该接口将要被用于一个事件的代理方案。 +2. 向一个类添加数据类型: +这种情况是标记接口最初的目的,实现标记接口的类不需要定义任何接口方法(因为标记接口根本就没有方法),但是该类通过多态性变成一个接口类型。*/ +interface FlagInterface { +} + +class MammalInt implements AnimalInterface { + public void eat() { + System.out.println("MammalInt.eat()"); + } + + public void travel() { + System.out.println("MammalInt.travel()"); + } + + public int noOfLegs() { + return 0; + } + +} \ No newline at end of file From 18ae9516bbca2e31d7b6f3970e94bbdc6baa1682 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Fri, 30 Jun 2017 14:27:41 +0800 Subject: [PATCH 21/41] Package --- src/tutorial/Abstracts.java | 8 +++--- src/tutorial/Interfaces.java | 17 ++---------- src/tutorial/animals/Animal.java | 15 +++++++++++ src/tutorial/animals/MammalInt.java | 26 +++++++++++++++++++ src/tutorial/{ => employee}/Employee.java | 10 ++++--- src/tutorial/{ => employee}/EmployeeTest.java | 2 ++ 6 files changed, 55 insertions(+), 23 deletions(-) create mode 100644 src/tutorial/animals/Animal.java create mode 100644 src/tutorial/animals/MammalInt.java rename src/tutorial/{ => employee}/Employee.java (61%) rename src/tutorial/{ => employee}/EmployeeTest.java (97%) diff --git a/src/tutorial/Abstracts.java b/src/tutorial/Abstracts.java index 561d275..f773ccf 100644 --- a/src/tutorial/Abstracts.java +++ b/src/tutorial/Abstracts.java @@ -4,7 +4,7 @@ public class Abstracts { public static void main(String[] args) { Salary s = new Salary("James Salary", "Shanghai", 7, 20000); - AbstractEmployee e = new Salary("John Employee", "Tokyo", 9, 30000); + Employee e = new Salary("John Employee", "Tokyo", 9, 30000); System.out.println("Call mailCheck using Salary reference --"); s.mailCheck(); @@ -16,7 +16,7 @@ public static void main(String[] args) { } -class Salary extends AbstractEmployee { +class Salary extends Employee { private double salary; public Salary(String name, String address, int number, double salary) { @@ -54,12 +54,12 @@ public void mailCheck() { 4. 构造方法,类方法(用static修饰的方法)不能声明为抽象方法。 5. 抽象类的子类必须给出抽象类中的抽象方法的具体实现,除非该子类也是抽象类。 */ -abstract class AbstractEmployee { +abstract class Employee { private String name; private String address; private int number; - public AbstractEmployee(String name, String address, int number) { + public Employee(String name, String address, int number) { System.out.println("Constructing an Employee"); this.name = name; this.address = address; diff --git a/src/tutorial/Interfaces.java b/src/tutorial/Interfaces.java index eb07d97..4faa465 100644 --- a/src/tutorial/Interfaces.java +++ b/src/tutorial/Interfaces.java @@ -1,3 +1,5 @@ +import animals.MammalInt; + /** * Created by Oliver on 30/06/2017. */ @@ -55,18 +57,3 @@ interface Hockey extends Sports { 这种情况是标记接口最初的目的,实现标记接口的类不需要定义任何接口方法(因为标记接口根本就没有方法),但是该类通过多态性变成一个接口类型。*/ interface FlagInterface { } - -class MammalInt implements AnimalInterface { - public void eat() { - System.out.println("MammalInt.eat()"); - } - - public void travel() { - System.out.println("MammalInt.travel()"); - } - - public int noOfLegs() { - return 0; - } - -} \ No newline at end of file diff --git a/src/tutorial/animals/Animal.java b/src/tutorial/animals/Animal.java new file mode 100644 index 0000000..1e820d9 --- /dev/null +++ b/src/tutorial/animals/Animal.java @@ -0,0 +1,15 @@ +package animals; + +/** + * Created by Oliver on 30/06/2017. + */ +public interface Animal { + /*接口是隐式抽象的,当声明一个接口的时候,不必使用abstract关键字。 + 接口中每一个方法也是隐式抽象的,声明时同样不需要abstract关键子。 + 接口中的方法都是公有的。 + */ + + void eat(); + + void travel(); +} diff --git a/src/tutorial/animals/MammalInt.java b/src/tutorial/animals/MammalInt.java new file mode 100644 index 0000000..02e953b --- /dev/null +++ b/src/tutorial/animals/MammalInt.java @@ -0,0 +1,26 @@ +package animals; + +/** + * Created by Oliver on 30/06/2017. + */ +public class MammalInt implements Animal { + public void eat() { + System.out.println("animals.Mammal eats"); + + } + + public void travel() { + System.out.println("animals.Mammal travels"); + + } + + public int noOfLegs() { + return 0; + } + + public static void main(String[] args) { + MammalInt mammalInt = new MammalInt(); + mammalInt.eat(); + mammalInt.travel(); + } +} diff --git a/src/tutorial/Employee.java b/src/tutorial/employee/Employee.java similarity index 61% rename from src/tutorial/Employee.java rename to src/tutorial/employee/Employee.java index 71e6b08..a2c8537 100644 --- a/src/tutorial/Employee.java +++ b/src/tutorial/employee/Employee.java @@ -1,3 +1,5 @@ +package employee; + /** * Created by Oliver on 25/06/2017. */ @@ -24,10 +26,10 @@ public void setDesignation(String designation) { } public void printEmployee() { - System.out.println("Employee name: " + this.name); - System.out.println("Employee age: " + this.age); - System.out.println("Employee designation: " + this.designation); - System.out.println("Employee salary: " + this.salary); + System.out.println("employee.Employee name: " + this.name); + System.out.println("employee.Employee age: " + this.age); + System.out.println("employee.Employee designation: " + this.designation); + System.out.println("employee.Employee salary: " + this.salary); } } diff --git a/src/tutorial/EmployeeTest.java b/src/tutorial/employee/EmployeeTest.java similarity index 97% rename from src/tutorial/EmployeeTest.java rename to src/tutorial/employee/EmployeeTest.java index 290cec9..e0037c7 100644 --- a/src/tutorial/EmployeeTest.java +++ b/src/tutorial/employee/EmployeeTest.java @@ -1,3 +1,5 @@ +package employee; + /** * Created by Oliver on 25/06/2017. */ From dd2289c088c9d885875ca741902ad5df9301cf8c Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Fri, 30 Jun 2017 15:43:55 +0800 Subject: [PATCH 22/41] BitSet, Enumeration, Stack, Vector --- src/tutorial/data/BitSets.java | 37 +++++++++++++++++++ src/tutorial/data/Enumerations.java | 33 +++++++++++++++++ src/tutorial/data/Stacks.java | 47 ++++++++++++++++++++++++ src/tutorial/data/Vectors.java | 57 +++++++++++++++++++++++++++++ 4 files changed, 174 insertions(+) create mode 100644 src/tutorial/data/BitSets.java create mode 100644 src/tutorial/data/Enumerations.java create mode 100644 src/tutorial/data/Stacks.java create mode 100644 src/tutorial/data/Vectors.java diff --git a/src/tutorial/data/BitSets.java b/src/tutorial/data/BitSets.java new file mode 100644 index 0000000..d916dcb --- /dev/null +++ b/src/tutorial/data/BitSets.java @@ -0,0 +1,37 @@ +package data; + +import java.util.BitSet; + +/** + * Created by Oliver on 30/06/2017. + */ + +/** + * 一个BitSet类创建一种特殊类型的数组来保存位值。BitSet中数组大小会随需要增加。这和位向量(vector of bits)比较类似。 + */ +public class BitSets { + public static void main(String[] args) { + BitSet bs1 = new java.util.BitSet(16); + BitSet bs2 = new java.util.BitSet(16); + + for (int i = 1; i <= 16; i++) { + if (i % 2 == 0) { + bs1.set(i); + } else if (i % 3 == 0) { + bs2.set(i); + } + } + System.out.println("BitSet1: " + bs1.toString()); + System.out.println("BitSet2: " + bs2.toString()); + + bs2.and(bs1); + System.out.println("BitSet2.and(BitSet1): " + bs2.toString()); + + bs2.or(bs1); + System.out.println("BitSet2.or(BitSet1): " + bs2.toString()); + + bs2.xor(bs1); + System.out.println("BitSet2.xor(BitSet1): " + bs2.toString()); + + } +} diff --git a/src/tutorial/data/Enumerations.java b/src/tutorial/data/Enumerations.java new file mode 100644 index 0000000..aa67d35 --- /dev/null +++ b/src/tutorial/data/Enumerations.java @@ -0,0 +1,33 @@ +package data; + +import java.util.Enumeration; +import java.util.Vector; + +/** + * Created by Oliver on 30/06/2017. + */ + +/** + * 枚举(Enumeration)接口虽然它本身不属于数据结构,但它在其他数据结构的范畴里应用很广。 枚举(The Enumeration)接口定义了一种从数据结构中取回连续元素的方式。 + * 例如,枚举定义了一个叫nextElement 的方法,该方法用来得到一个包含多元素的数据结构的下一个元素。 + * + * boolean hasMoreElements( ) 测试此枚举是否包含更多的元素。 + * Object nextElement( ) 如果此枚举对象至少还有一个可提供的元素,则返回此枚举的下一个元素。 + */ +public class Enumerations { + public static void main(String[] args) { + Enumeration days; + Vector dayNames = new Vector(); + dayNames.add("Sunday"); + dayNames.add("Monday"); + dayNames.add("Tuesday"); + dayNames.add("Wednesday"); + dayNames.add("Thursday"); + dayNames.add("Friday"); + dayNames.add("Saturday"); + days = dayNames.elements(); + while (days.hasMoreElements()) { + System.out.println(days.nextElement()); + } + } +} diff --git a/src/tutorial/data/Stacks.java b/src/tutorial/data/Stacks.java new file mode 100644 index 0000000..8dd2b33 --- /dev/null +++ b/src/tutorial/data/Stacks.java @@ -0,0 +1,47 @@ +package data; + +import java.util.EmptyStackException; +import java.util.Stack; + +/** + * Created by Oliver on 30/06/2017. + */ + +/** + * 栈是Vector的一个子类,它实现了一个标准的后进先出的栈。 + * 堆栈只定义了默认构造函数,用来创建一个空栈。 堆栈除了包括由Vector定义的所有方法,也定义了自己的一些方法。 + */ +public class Stacks { + static void tryPush(Stack stack, int i) { + stack.push(i); + System.out.printf("Push %d to stack %s%n", i, stack); + } + + static void tryPop(Stack stack) { + Integer popped = (Integer) stack.pop(); + System.out.printf("Pop %d off stack %s%n", popped, stack); + } + + + public static void main(String[] args) { + Stack stack = new Stack(); + tryPush(stack, 10); + tryPush(stack, 20); + tryPush(stack, 30); + tryPush(stack, 40); + tryPush(stack, 50); + tryPop(stack); + tryPop(stack); + tryPop(stack); + tryPop(stack); + tryPop(stack); + + try { + tryPop(stack); + } catch (EmptyStackException e) { + System.out.println("empty stack"); + e.printStackTrace(); + } + } + +} diff --git a/src/tutorial/data/Vectors.java b/src/tutorial/data/Vectors.java new file mode 100644 index 0000000..a5923e3 --- /dev/null +++ b/src/tutorial/data/Vectors.java @@ -0,0 +1,57 @@ +package data; + +import java.util.Enumeration; +import java.util.Vector; + +/** + * Created by Oliver on 30/06/2017. + */ + +/** + * Vector类实现了一个动态数组。和ArrayList和相似,但是两者是不同的: + * Vector是同步访问的。 + * Vector包含了许多传统的方法,这些方法不属于集合框架。 + * Vector主要用在事先不知道数组的大小,或者只是需要一个可以改变大小的数组的情况。 + */ +public class Vectors { + public static void main(String[] args) { + Vector v = new Vector(3, 2); + System.out.printf("Initial size: %d%n", v.size()); + System.out.printf("Initial capacity: %d%n", v.capacity()); + + v.addElement(new Integer(1)); + v.addElement(new Integer(2)); + v.addElement(new Integer(3)); + v.addElement(new Integer(4)); + System.out.printf("Capacity after 4 additions: %d%n", v.capacity()); + + v.addElement(new Double(3.14)); + System.out.printf("Capacity after 5 additions: %d%n", v.capacity()); + + v.addElement(new Double(6.08)); + v.addElement(new Integer(7)); + System.out.printf("Capacity after 7 additions: %d%n", v.capacity()); + + v.addElement(new Float(9.4)); + v.addElement(new Integer(10)); + System.out.printf("Capacity after 9 additions: %d%n", v.capacity()); + + v.addElement(new Integer(11)); + v.addElement(new Integer(12)); + System.out.printf("Capacity after 11 additions: %d%n", v.capacity()); + + System.out.println("1st element: " + v.firstElement()); + System.out.println("last element: " + v.lastElement()); + + if (v.contains(3)) { + System.out.println("Vector contains 3"); + } + + Enumeration enumeration = v.elements(); + while (enumeration.hasMoreElements()) { + System.out.println(enumeration.nextElement()); + } + + System.out.printf("Size in the end: %d%n", v.size()); + } +} From 295ee520f5b16aa6021a46989dfa3e44f2b7458f Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Fri, 30 Jun 2017 17:58:33 +0800 Subject: [PATCH 23/41] Map, Hashtable, Properties --- src/tutorial/data/Hashtables.java | 34 +++++++++++++++++++++++++++ src/tutorial/data/Maps.java | 39 +++++++++++++++++++++++++++++++ src/tutorial/data/Propertys.java | 35 +++++++++++++++++++++++++++ 3 files changed, 108 insertions(+) create mode 100644 src/tutorial/data/Hashtables.java create mode 100644 src/tutorial/data/Maps.java create mode 100644 src/tutorial/data/Propertys.java diff --git a/src/tutorial/data/Hashtables.java b/src/tutorial/data/Hashtables.java new file mode 100644 index 0000000..b65b7b7 --- /dev/null +++ b/src/tutorial/data/Hashtables.java @@ -0,0 +1,34 @@ +package data; + +import java.util.Enumeration; +import java.util.Hashtable; + +/** + * Created by Oliver on 30/06/2017. + */ + +/** + * Hashtable是原始的java.util的一部分, 是一个Dictionary具体的实现 。 + * 然而,Java 2 重构的Hashtable实现了Map接口,因此,Hashtable现在集成到了集合框架中。它和HashMap类很相似,但是它支持同步。 + * 像HashMap一样,Hashtable在哈希表中存储键/值对。当使用一个哈希表,要指定用作键的对象,以及要链接到该键的值。 + * 然后,该键经过哈希处理,所得到的散列码被用作存储在该表中值的索引。 + */ +public class Hashtables { + public static void main(String[] args) { + Hashtable hashtable = new Hashtable(); + hashtable.put("Java", new Double(1.11)); + hashtable.put("Python", new Double(2.22)); + hashtable.put("Go", new Double(3.33)); + + Enumeration languages = hashtable.keys(); // 返回此哈希表中的键的枚举 + while (languages.hasMoreElements()) { + String language = (String) languages.nextElement(); + System.out.println(language + ": " + hashtable.get(language)); + } + + Double d = (Double) hashtable.get("Python") + 7.77; + hashtable.put("Python", d); + System.out.println("Python's new value: " + hashtable.get("Python")); + + } +} diff --git a/src/tutorial/data/Maps.java b/src/tutorial/data/Maps.java new file mode 100644 index 0000000..da76277 --- /dev/null +++ b/src/tutorial/data/Maps.java @@ -0,0 +1,39 @@ +package data; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * Created by Oliver on 30/06/2017. + */ + +/** + * Map接口中键和值一一映射. 可以通过键来获取值。 + * 给定一个键和一个值,你可以将该值存储在一个Map对象. 之后,你可以通过键来访问对应的值。 + * 当访问的值不存在的时候,方法就会抛出一个NoSuchElementException异常. + * 当对象的类型和Map里元素类型不兼容的时候,就会抛出一个 ClassCastException异常。 + * 当在不允许使用Null对象的Map中使用Null对象,会抛出一个NullPointerException 异常。 + * 当尝试修改一个只读的Map时,会抛出一个UnsupportedOperationException异常。 + */ +public class Maps { + public static void main(String[] args) { + Map map = new HashMap(); + map.put("Python", 1); + map.put("Java", 2); + map.put("Go", 3); + System.out.println("map elements: " + map); + System.out.println("map.size(): " + map.size()); + System.out.println("map.containsKey('Python'): " + map.containsKey("Python")); + System.out.println("map.containsValue(3): " + map.containsValue(3)); + + Set s = map.entrySet(); + System.out.println("映射中包含的映射关系的 Set 视图: " + s); + + Collection c = map.values(); + System.out.println("映射中包含的值的 Collection 视图: " + c); + + } + +} diff --git a/src/tutorial/data/Propertys.java b/src/tutorial/data/Propertys.java new file mode 100644 index 0000000..3c24c35 --- /dev/null +++ b/src/tutorial/data/Propertys.java @@ -0,0 +1,35 @@ +package data; + +import java.util.Iterator; +import java.util.Properties; +import java.util.Set; + +/** + * Created by Oliver on 30/06/2017. + */ + +/** + * Properties 继承于 Hashtable.Properties 类表示了一个持久的属性集.属性列表中每个键及其对应值都是一个字符串。 + * Properties 类被许多Java类使用。例如,在获取环境变量时它就作为System.getProperties()方法的返回值。 + */ +public class Propertys { + public static void main(String[] args) { + System.out.println(System.getProperties()); + + Properties properties = new Properties(); + properties.put("JAVA", "java"); + properties.put("PYTHON", "python"); + properties.put("GO", "go"); + + Set languages = properties.keySet(); + Iterator iterator = languages.iterator(); + while (iterator.hasNext()) { + String language = (String) iterator.next(); + System.out.printf("%s turned to lowercase: %s%n", language, properties.getProperty(language, "C++")); + } + + // 用指定的键在属性列表中搜索属性, 不存在就返回默认值 + System.out.printf("%s turned to lowercase: %s%n", "RUBY", properties.getProperty("RUBY", "c++")); + + } +} From bd581d4a227e45faf5910f3835ebf50ad1efae6e Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Sat, 1 Jul 2017 16:13:15 +0800 Subject: [PATCH 24/41] Collection --- src/tutorial/data/Collection.java | 116 ++++++++++++++++++++++++++++++ src/tutorial/data/Propertys.java | 2 +- 2 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 src/tutorial/data/Collection.java diff --git a/src/tutorial/data/Collection.java b/src/tutorial/data/Collection.java new file mode 100644 index 0000000..a85a185 --- /dev/null +++ b/src/tutorial/data/Collection.java @@ -0,0 +1,116 @@ +package data; + +import java.util.*; + +/** + * Created by Oliver on 01/07/2017. + */ +public class Collection { + /** + * 集合接口 + *1 Collection 是最基本的集合接口,一个 Collection 代表一组 Object,Java不提供直接继承自Collection的类,只提供继承于的子接口(如List和set)。 + *2 List接口是一个有序的Collection,使用此接口能够精确的控制每个元素插入的位置,能够通过索引(元素在List中位置,类似于数组的小标)来访问List中的元素,而且允许有相同的元素。 + *3 Set 具有与 Collection 完全一样的接口,只是行为上不同,Set 不保存重复的元素。 + *4 SortedSet继承于Set保存有序的集合。 + *5 Map将唯一的键映射到值。 + *6 Map.Entry描述在一个Map中的一个元素(键/值对)。是一个Map的内部类。 + *7 SortedMap继承于Map,使Key保持在升序排列。 + *8 Enumeration这是一个传统的接口和定义的方法,通过它可以枚举(一次获得一个)对象集合中的元素。这个传统接口已被迭代器取代。 + */ + + /** + * 集合实现类 + * 1 AbstractCollection 实现了大部分的集合接口。 + * 2 AbstractList 继承于AbstractCollection 并且实现了大部分List接口。 + * 3 AbstractSequentialList 继承于 AbstractList ,提供了对数据元素的链式访问而不是随机访问。 + * 4 LinkedList该类实现了List接口,允许有null(空)元素。主要用于创建链表数据结构,该类没有同步方法,如果多个线程同时访问一个List,则必须自己实现访问同步,解决方法就是在创建List时候构造一个同步的List。 + * 例如:Listlist=Collections.synchronizedList(newLinkedList(...));LinkedList 查找效率低。 + * 5 ArrayList该类也是实现了List的接口,实现了可变大小的数组,随机访问和遍历元素时,提供更好的性能。该类也是非同步的,在多线程的情况下不要使用。ArrayList 增长当前长度的50%,插入删除效率低。 + * 6 AbstractSet 继承于AbstractCollection 并且实现了大部分Set接口。 + * 7 HashSet该类实现了Set接口,不允许出现重复元素,不保证集合中元素的顺序,允许包含值为null的元素,但最多只能一个。 + * 8 LinkedHashSet具有可预知迭代顺序的 Set 接口的哈希表和链接列表实现。 + * 9 TreeSet该类实现了Set接口,可以实现排序等功能。 + * 10 AbstractMap 实现了大部分的Map接口。 + * 11 HashMap 是一个散列表,它存储的内容是键值对(key-value)映射。 + * 该类实现了Map接口,根据键的HashCode值存储数据,具有很快的访问速度,最多允许一条记录的键为null,不支持线程同步。 + * 12 TreeMap 继承了AbstractMap,并且使用一颗树。 + * 13 WeakHashMap 继承AbstractMap类,使用弱密钥的哈希表。 + * 14 LinkedHashMap 继承于HashMap,使用元素的自然顺序对元素进行排序. + * 15 IdentityHashMap 继承AbstractMap类,比较文档时使用引用相等。 + */ + + /** + * 通过java.util包中定义的类 + * 1 Vector 该类和ArrayList非常相似,但是该类是同步的,可以用在多线程的情况,该类允许设置默认的增长长度,默认扩容方式为原来的2倍。 + * 2 Stack 栈是Vector的一个子类,它实现了一个标准的后进先出的栈。 + * 3 Dictionary 类是一个抽象类,用来存储键/值对,作用和Map类相似。 + * 4 Hashtable 是 Dictionary(字典) 类的子类,位于 java.util 包中。 + * 5 Properties 继承于 Hashtable,表示一个持久的属性集,属性列表中每个键及其对应值都是一个字符串。 + * 6 BitSet类创建一种特殊类型的数组来保存位值。BitSet中数组大小会随需要增加。 + */ + public static void main(String[] args) { + traverse_ArrayList(); + traverse_map(); + } + + public static void traverse_ArrayList() { + System.out.println("\n*****遍历 ArrayList*****:"); + List list = new ArrayList(); + list.add("Java"); + list.add("Python"); + list.add("Go"); + + //第一种遍历方法使用foreach遍历List + System.out.println("第一种遍历, 使用foreach遍历List:"); + for (String language : list) { + System.out.println(language); + } + + //第二种遍历,把链表变为数组相关的内容进行遍历 + System.out.println("第二种遍历,把链表变为数组相关的内容进行遍历:"); + String[] strArray = new String[list.size()]; + list.toArray(strArray); + for (String language : strArray) { + System.out.println(language); + } + + //第三种遍历 使用迭代器进行相关遍历 + System.out.println("第三种遍历, 使用迭代器进行相关遍历:"); + Iterator iterator = list.iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); + } + } + + public static void traverse_map() { + System.out.println("\n*****遍历 Map*****:"); + Map map = new HashMap(); + map.put("Java", "JAVA"); + map.put("Python", "PYTHON"); + map.put("Go", "GO"); + + //第一种:普遍使用,二次取值 + System.out.println("第一种:普遍使用,二次取值:"); + for (String key : map.keySet()) { + System.out.printf("%s: %s%n", key, map.get(key)); //通过Map.keySet遍历key和value + } + + System.out.println("第二种:通过Map.entrySet使用iterator遍历key和value:"); + Iterator iterator = map.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry entry = (Map.Entry) iterator.next(); + System.out.printf("%s: %s%n", entry.getKey(), entry.getValue()); + } + + System.out.println("第三种:通过Map.entrySet遍历key和value:"); + for (Map.Entry entry : map.entrySet()) { + System.out.printf("%s: %s%n", entry.getKey(), entry.getValue()); + } + + System.out.println("第四种: 通过Map.values()遍历所有的value,但不能遍历key:"); + for (String value : map.values()) { + System.out.printf("%s%n", value); + } + + } +} diff --git a/src/tutorial/data/Propertys.java b/src/tutorial/data/Propertys.java index 3c24c35..af3abc0 100644 --- a/src/tutorial/data/Propertys.java +++ b/src/tutorial/data/Propertys.java @@ -9,7 +9,7 @@ */ /** - * Properties 继承于 Hashtable.Properties 类表示了一个持久的属性集.属性列表中每个键及其对应值都是一个字符串。 + * Properties 继承于 Hashtable. Properties 类表示了一个持久的属性集.属性列表中每个键及其对应值都是一个字符串。 * Properties 类被许多Java类使用。例如,在获取环境变量时它就作为System.getProperties()方法的返回值。 */ public class Propertys { From 5e710446390b1da13bd1ef76e7717c6951338dc4 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Sat, 1 Jul 2017 17:56:40 +0800 Subject: [PATCH 25/41] Generic --- src/tutorial/data/Generics.java | 116 ++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 src/tutorial/data/Generics.java diff --git a/src/tutorial/data/Generics.java b/src/tutorial/data/Generics.java new file mode 100644 index 0000000..f278aab --- /dev/null +++ b/src/tutorial/data/Generics.java @@ -0,0 +1,116 @@ +package data; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Oliver on 01/07/2017. + */ +public class Generics { + public static void main(String[] args) { + Integer[] intArray = {2, 4, 6}; + String[] strArray = {"Python", "Java", "Go"}; + Character[] charArray = {'a', 'b', 'c'}; + System.out.println("整型数组元素为:"); + printArray(intArray); + System.out.println("\n双精度型数组元素为:"); + printArray(strArray); + System.out.println("\n字符型数组元素为:"); + printArray(charArray); + + System.out.printf("Max int: %d%n", maximum(1, 2, 3)); + System.out.printf("Max str: %s%n", maximum("apple", "banana", "pineapple")); + System.out.printf("Max double: %f%n", maximum(0.12, 2.12, 10.3)); + + Box integerBox = new Box(); + Box stringBox = new Box(); + Box doulbeBox = new Box(); + integerBox.setT(10); + stringBox.setT("Python"); + doulbeBox.setT(10.10); + + System.out.printf("Box: %d%n", integerBox.getT()); + System.out.printf("Box: %s%n", stringBox.getT()); + System.out.printf("Box: %f%n", doulbeBox.getT()); + + List integerArrayList = new ArrayList<>(); + List stringArrayList = new ArrayList<>(); + List doubleArrayList = new ArrayList<>(); + integerArrayList.add(7); + stringArrayList.add("Python"); + doubleArrayList.add(7.7); + getData(integerArrayList); //类型通配符List,在逻辑上是List,List 等所有List<具体类型实参>的父类 + getData(stringArrayList); + getData(doubleArrayList); + + getNumber(integerArrayList); + // getNumber(stringArrayList); // 参数泛型上限为Number,所以泛型为String是不在这个范围之内,所以会报错 + getNumber(doubleArrayList); + + + } + + /** + * 泛型方法 printArray + */ + public static void printArray(E[] inputArray) { + for (E element : inputArray) { + System.out.println(element); + } + } + + /** + * 有界的类型参数 + * 可能有时候,你会想限制那些被允许传递到一个类型参数的类型种类范围。 + * 例如,一个操作数字的方法可能只希望接受Number或者Number子类的实例。这就是有界类型参数的目的。 + * 要声明一个有界的类型参数,首先列出类型参数的名称,后跟extends关键字,最后紧跟它的上界 + * 该例子中的泛型方法返回三个可比较对象的最大值 + */ + public static > T maximum(T a, T b, T c) { + T max = a; + if (b.compareTo(max) > 0) { + max = b; + } + if (c.compareTo(max) > 0) { + max = c; + } + return max; + } + + /** + * 类型通配符 + * 因为getDate()方法的参数是List类型的,所以integerArrayList,stringArrayList,doubleArrayList都可以作为这个方法的实参,这就是通配符的作用 + */ + public static void getData(List data) { + System.out.printf("Data Class: %s, Data Value: %s%n", data.get(0).getClass(), data.get(0)); + } + + /** + * 类型通配符上限通过形如List来定义,如此定义就是通配符泛型值接受Number及其下层子类类型 + * 表示该通配符所代表的类型是T类型的子类。 + * 表示该通配符所代表的类型是T类型的父类。 + */ + public static void getNumber(List number) { + System.out.printf("Number Class: %s, Number Value: %s%n", number.get(0).getClass(), number.get(0)); + } +} + +/** + * 定义一个泛型类 + * 泛型类的声明和非泛型类的声明类似,除了在类名后面添加了类型参数声明部分。 + * 和泛型方法一样,泛型类的类型参数声明部分也包含一个或多个类型参数,参数间用逗号隔开。 + * 一个泛型参数,也被称为一个类型变量,是用于指定一个泛型类型名称的标识符。 + * 因为他们接受一个或多个参数,这些类被称为参数化的类或参数化的类型。 + */ +class Box { + private T t; + + public void setT(T t) { + this.t = t; + } + + public T getT() { + return t; + } +} + From 3ad8de5d39fcdeb69faeb56372e41b06e082a6f6 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Sun, 2 Jul 2017 16:30:12 +0800 Subject: [PATCH 26/41] Serializable --- .gitignore | 2 +- src/tutorial/employee/Employee.java | 20 +++++++- src/tutorial/{ => file}/Files.java | 2 + src/tutorial/file/Serializables.java | 68 +++++++++++++++++++++++++++ src/tutorial/file/employee.ser | Bin 0 -> 132 bytes 5 files changed, 90 insertions(+), 2 deletions(-) rename src/tutorial/{ => file}/Files.java (99%) create mode 100644 src/tutorial/file/Serializables.java create mode 100644 src/tutorial/file/employee.ser diff --git a/.gitignore b/.gitignore index 57a89ad..08f682a 100644 --- a/.gitignore +++ b/.gitignore @@ -16,7 +16,7 @@ interfacetest.iml # Mobile Tools for Java (J2ME) .mtj.tmp/ -# Package Files # +# Package file.Files # #*.jar *.war *.ear diff --git a/src/tutorial/employee/Employee.java b/src/tutorial/employee/Employee.java index a2c8537..7ccf0d9 100644 --- a/src/tutorial/employee/Employee.java +++ b/src/tutorial/employee/Employee.java @@ -1,9 +1,11 @@ package employee; +import java.io.Serializable; + /** * Created by Oliver on 25/06/2017. */ -public class Employee { +public class Employee implements Serializable { int age; double salary; String name; @@ -25,6 +27,22 @@ public void setDesignation(String designation) { this.designation = designation; } + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + public double getSalary() { + return salary; + } + + public String getDesignation() { + return designation; + } + public void printEmployee() { System.out.println("employee.Employee name: " + this.name); System.out.println("employee.Employee age: " + this.age); diff --git a/src/tutorial/Files.java b/src/tutorial/file/Files.java similarity index 99% rename from src/tutorial/Files.java rename to src/tutorial/file/Files.java index 43cdc90..d9ad243 100644 --- a/src/tutorial/Files.java +++ b/src/tutorial/file/Files.java @@ -1,3 +1,5 @@ +package file; + import java.io.*; /** diff --git a/src/tutorial/file/Serializables.java b/src/tutorial/file/Serializables.java new file mode 100644 index 0000000..5686a62 --- /dev/null +++ b/src/tutorial/file/Serializables.java @@ -0,0 +1,68 @@ +package file; + +import employee.Employee; + +import java.io.*; + +/** + * Created by Oliver on 02/07/2017. + */ +public class Serializables { + public static void main(String[] args) { + serialize(); + deserialize(); + } + + public static void serialize() { + /** + * ObjectOutputStream 类用来序列化一个对象 + * 如下例子实例化了一个 Employee 对象,并将该对象序列化到一个文件中。 + */ + Employee employee = new Employee("Austin"); + employee.setAge(30); + employee.setDesignation("Engineer"); + employee.setSalary(30000); + + try { + FileOutputStream fileOutputStream = new FileOutputStream("src/tutorial/file/employee.ser"); + ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); + objectOutputStream.writeObject(employee); + objectOutputStream.close(); + fileOutputStream.close(); + System.out.println("Serialized data is saved as: src/tutorial/file/employee.ser"); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void deserialize() { + /** + * 下面的 DeserializeDemo 程序实例了反序列化,employee.ser 存储了 Employee 对象。 + */ + Employee employee; + try { + FileInputStream fileInputStream = new FileInputStream("src/tutorial/file/employee.ser"); + ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); + employee = (Employee) objectInputStream.readObject(); //readObject() 方法的返回值被转化成 Employee 引用 + objectInputStream.close(); + fileInputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + return; + } catch (ClassNotFoundException c) { + /** + 对于 JVM 可以反序列化对象,它必须是能够找到字节码的类。 + 如果JVM在反序列化对象的过程中找不到该类,则抛出一个 ClassNotFoundException 异常 + */ + c.printStackTrace(); + return; + } + System.out.println("Deserialize Employee..."); + System.out.println("Employee name: " + employee.getName()); + System.out.println("Employee age: " + employee.getAge()); + System.out.println("Employee designation: " + employee.getDesignation()); + System.out.println("Employee salary: " + employee.getSalary()); + + } +} diff --git a/src/tutorial/file/employee.ser b/src/tutorial/file/employee.ser new file mode 100644 index 0000000000000000000000000000000000000000..59881c790a2985a26048b8d9fc2cde9ca93a24fc GIT binary patch literal 132 zcmZ4UmVvdnh(Rzlw;(6KGBs7t70S3}o518(IAJ;y1B)jEb7Fd`3jFVp*boPGVlVesD=qW?s6r4+BeHVs2_7LmdNSMF9f?gPg-% dA0WlRP{P3BnwOrLmzr8s!ocQOT3nKu2LL!KDG&ev literal 0 HcmV?d00001 From 2804af0bce2c85b0176e4d6265119d2a4416ef3d Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Tue, 4 Jul 2017 17:48:16 +0800 Subject: [PATCH 27/41] JavaMail --- pom.xml | 2 +- src/tutorial/mails/JavaMail.java | 147 +++++++++++++++++++++++++++++ src/tutorial/mails/TestMail.java | 17 ++++ src/tutorial/mails/smtp.properties | 4 + 4 files changed, 169 insertions(+), 1 deletion(-) create mode 100644 src/tutorial/mails/JavaMail.java create mode 100644 src/tutorial/mails/TestMail.java create mode 100644 src/tutorial/mails/smtp.properties diff --git a/pom.xml b/pom.xml index 5f8be67..10e1793 100644 --- a/pom.xml +++ b/pom.xml @@ -186,7 +186,7 @@ com.sun.mail javax.mail - 1.4.4 + 1.4.7 diff --git a/src/tutorial/mails/JavaMail.java b/src/tutorial/mails/JavaMail.java new file mode 100644 index 0000000..3d10dd5 --- /dev/null +++ b/src/tutorial/mails/JavaMail.java @@ -0,0 +1,147 @@ +package mails; + +import javax.activation.DataHandler; +import javax.activation.FileDataSource; +import javax.mail.*; +import javax.mail.internet.*; +import java.io.IOException; +import java.io.InputStream; +import java.security.Security; +import java.util.Properties; + +/** + * Created by Oliver on 03/07/2017. + */ +public class JavaMail { + private String to = ""; + private String from = ""; + private String password = ""; + private String host = ""; + private Properties properties = System.getProperties(); + private boolean debug = false; + + public JavaMail(boolean debug) { + InputStream in = JavaMail.class.getResourceAsStream("smtp.properties"); + try { + properties.load(in); + to = properties.getProperty("mail.sender.send.to"); + from = properties.getProperty("mail.sender.username"); + password = properties.getProperty("mail.sender.password"); + host = properties.getProperty("mail.smtp.host"); + } catch (IOException e) { + e.printStackTrace(); + } + this.debug = debug; + } + + + public void init() { + //设置SSL连接、邮件环境 + Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); + final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; + properties.setProperty("mail.smtp.host", host); // 设置邮件服务器 + properties.setProperty("mail.smtp.auth", "true"); + properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); + properties.setProperty("mail.smtp.socketFactory.fallback", "false"); + properties.setProperty("mail.smtp.port", "465"); + properties.setProperty("mail.smtp.socketFactory.port", "465"); + } + + public void plain_mail(String subject, String text) { + init(); + // 获取默认session对象 + Session session = Session.getDefaultInstance(properties, new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(from, password); + } + }); + + session.setDebug(debug); + + try { + MimeMessage mimeMessage = new MimeMessage(session); + mimeMessage.setFrom(new InternetAddress(from)); + mimeMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to)); + + mimeMessage.setSubject(subject); + mimeMessage.setText(text); // 设置消息体 + Transport.send(mimeMessage); + System.out.println("Sent plain message successfully...."); + } catch (AddressException a) { + a.printStackTrace(); + } catch (MessagingException m) { + m.printStackTrace(); + } + } + + public void html_mail(String subject, String content) { + init(); + Session session = Session.getDefaultInstance(properties, new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(from, password); + } + }); + + session.setDebug(debug); + + try { + MimeMessage mimeMessage = new MimeMessage(session); + mimeMessage.setFrom(new InternetAddress(from)); + mimeMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to)); + mimeMessage.setSubject(subject); + mimeMessage.setContent(content, "text/html"); // 发送 HTML 消息, 可以插入html标签 + Transport.send(mimeMessage); + System.out.println("Sent html message successfully...."); + } catch (AddressException a) { + a.printStackTrace(); + } catch (MessagingException m) { + m.printStackTrace(); + } + } + + public void attachment_mail(String subject, String text, String filePath) { + init(); + Session session = Session.getDefaultInstance(properties, new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(from, password); + } + }); + + session.setDebug(debug); + + try { + // 创建默认的 MimeMessage 对象 + MimeMessage mimeMessage = new MimeMessage(session); + mimeMessage.setFrom(new InternetAddress(from)); + mimeMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to)); + mimeMessage.setSubject(subject); + + // 创建消息部分 + BodyPart bodyPart = new MimeBodyPart(); + bodyPart.setText(text); + + // 设置文本消息部分 + FileDataSource fileDataSource = new FileDataSource(filePath); + bodyPart.setDataHandler(new DataHandler(fileDataSource)); + bodyPart.setFileName(filePath); + + // 创建多重消息 + Multipart multipart = new MimeMultipart(); + multipart.addBodyPart(bodyPart); + + // 发送完整消息 + mimeMessage.setContent(multipart); + + // 发送消息 + Transport.send(mimeMessage); + System.out.println("Sent attachment message successfully...."); + + } catch (MessagingException m) { + m.printStackTrace(); + } + } + +} diff --git a/src/tutorial/mails/TestMail.java b/src/tutorial/mails/TestMail.java new file mode 100644 index 0000000..e058be4 --- /dev/null +++ b/src/tutorial/mails/TestMail.java @@ -0,0 +1,17 @@ +package mails; + +import java.io.File; + +/** + * Created by Oliver on 04/07/2017. + */ +public class TestMail { + public static void main(String[] args) { + JavaMail javaMail = new JavaMail(true); + javaMail.plain_mail("Java smtp testing with plain content", "Plain Message using JavaMail"); + javaMail.html_mail("Java smtp testing with html content", "

HTML Message using JavaMail

"); + + String filePath = System.getProperty("user.dir") + File.separator + "pom.xml"; + javaMail.attachment_mail("Java smtp testing with attachment content", "Plain text with attachment", filePath); + } +} diff --git a/src/tutorial/mails/smtp.properties b/src/tutorial/mails/smtp.properties new file mode 100644 index 0000000..ca102a9 --- /dev/null +++ b/src/tutorial/mails/smtp.properties @@ -0,0 +1,4 @@ +mail.smtp.host=smtp.qq.com +mail.sender.username=82740301@qq.com +mail.sender.password=xpagwzokxmdzbjcb +mail.sender.send.to=oliver19830714@gmail.com From 3e8a98ac28f036d457927484e73a470a8f3505c9 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Wed, 5 Jul 2017 14:22:58 +0800 Subject: [PATCH 28/41] Runnable, Callable, Thread --- src/tutorial/threading/CallableDemo.java | 46 ++++++++++++++++++++ src/tutorial/threading/RunnableDemo.java | 53 ++++++++++++++++++++++++ src/tutorial/threading/ThreadDemo.java | 50 ++++++++++++++++++++++ 3 files changed, 149 insertions(+) create mode 100644 src/tutorial/threading/CallableDemo.java create mode 100644 src/tutorial/threading/RunnableDemo.java create mode 100644 src/tutorial/threading/ThreadDemo.java diff --git a/src/tutorial/threading/CallableDemo.java b/src/tutorial/threading/CallableDemo.java new file mode 100644 index 0000000..61a16e5 --- /dev/null +++ b/src/tutorial/threading/CallableDemo.java @@ -0,0 +1,46 @@ +package threading; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.FutureTask; + +/** + * Created by Oliver on 05/07/2017. + */ +public class CallableDemo implements Callable { + /** + * 创建 Callable 实现类的实例,使用 FutureTask 类来包装 Callable 对象, + * 该 FutureTask 对象封装了该 Callable 对象的 call() 方法的返回值。 + */ + public static void main(String[] args) { + CallableDemo callableDemo = new CallableDemo(); + FutureTask futureTask = new FutureTask(callableDemo); + for (int i = 0; i < 10; i++) { + System.out.println(Thread.currentThread().getName() + "线程的循环变量i: " + i); + if (i == 5) { + // 使用 FutureTask 对象作为 Thread 对象的 target 创建并启动新线程 + new Thread(futureTask, "有返回值的线程").start(); + } + } + try { + // 调用 FutureTask 对象的 get() 方法来获得子线程执行结束后的返回值 + System.out.println("子线程的返回值:" + futureTask.get()); + } catch (InterruptedException i) { + i.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } + } + + /** + * 该 call() 方法将作为线程执行体,并且有返回值 + */ + @Override + public Integer call() throws Exception { + int i = 0; + for (; i < 10; i++) { + System.out.println(Thread.currentThread().getName() + ": " + i); + } + return i; + } +} diff --git a/src/tutorial/threading/RunnableDemo.java b/src/tutorial/threading/RunnableDemo.java new file mode 100644 index 0000000..66f66de --- /dev/null +++ b/src/tutorial/threading/RunnableDemo.java @@ -0,0 +1,53 @@ +package threading; + +/** + * Created by Oliver on 05/07/2017. + */ +public class RunnableDemo implements Runnable { + private Thread t; + private String threadName; + + public RunnableDemo(String threadName) { + this.threadName = threadName; + System.out.println("Creating thread: " + threadName); + } + + public static void main(String[] args) { + RunnableDemo threadDemo1 = new RunnableDemo("Thread-1"); + RunnableDemo threadDemo2 = new RunnableDemo("Thread-2"); + + threadDemo1.start(); + threadDemo2.start(); + } + + /** + * 为了实现 Runnable,一个类只需要执行一个方法调用 run() + * run() 可以调用其他方法,使用其他类,并声明变量,就像主线程一样 + */ + public void run() { + System.out.println("Running thread: " + threadName); + try { + for (int i = 0; i < 5; i++) { + System.out.println("Thread: " + threadName + ": " + i); + Thread.sleep(50); + } + } catch (InterruptedException i) { + System.out.println("Thread " + threadName + "interrupted"); + } + System.out.println("Exit thread: " + threadName); + } + + /** + * Thread(Runnable threadOb,String threadName) + * threadOb 是一个实现 Runnable 接口的类的实例,并且 threadName 指定新线程的名字 + */ + public void start() { + System.out.println("***Starting thread " + threadName); + if (t == null) { + t = new Thread(this, threadName); + t.start(); // 新线程创建之后,你调用它的 start() 方法它才会运行 + + } + } + +} diff --git a/src/tutorial/threading/ThreadDemo.java b/src/tutorial/threading/ThreadDemo.java new file mode 100644 index 0000000..6cb0ba7 --- /dev/null +++ b/src/tutorial/threading/ThreadDemo.java @@ -0,0 +1,50 @@ +package threading; + +/** + * Created by Oliver on 05/07/2017. + */ +public class ThreadDemo extends Thread { + /** + * 创建一个线程的第二种方法是创建一个新的类,该类继承 Thread 类,然后创建一个该类的实例。 + * 该方法尽管被列为一种多线程实现方式,但是本质上也是实现了 Runnable 接口的一个实例。 + */ + private Thread t; + private String threadName; + + public ThreadDemo(String threadName) { + this.threadName = threadName; + } + + public static void main(String[] args) { + ThreadDemo threadDemo1 = new ThreadDemo("Thread-1"); + ThreadDemo threadDemo2 = new ThreadDemo("Thread=2"); + + threadDemo1.start(); + threadDemo2.start(); + } + + /** + * 继承类必须重写 run() 方法,该方法是新线程的入口点。它也必须调用 start() 方法才能执行。 + */ + public void run() { + System.out.println("Running thread: " + threadName); + try { + for (int i = 0; i < 5; i++) { + System.out.println("Thread: " + threadName + ": " + i); + Thread.sleep(50); + } + } catch (InterruptedException i) { + System.out.println("Thread " + threadName + " interrupted."); + } + System.out.println("Exit thread: " + threadName); + + } + + public void start() { + System.out.println("Start thread " + threadName); + if (t == null) { + t = new Thread(this, threadName); + t.start(); + } + } +} From 8e030b7118784cfb7a5a65698d46338a31aa9526 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Thu, 6 Jul 2017 13:31:34 +0800 Subject: [PATCH 29/41] Array, String --- src/tutorial/examples/ArrayExample.java | 184 +++++++++++++++++++++++ src/tutorial/examples/StringExample.java | 115 ++++++++++++++ 2 files changed, 299 insertions(+) create mode 100644 src/tutorial/examples/ArrayExample.java create mode 100644 src/tutorial/examples/StringExample.java diff --git a/src/tutorial/examples/ArrayExample.java b/src/tutorial/examples/ArrayExample.java new file mode 100644 index 0000000..5ed04b8 --- /dev/null +++ b/src/tutorial/examples/ArrayExample.java @@ -0,0 +1,184 @@ +package examples; + +import java.util.*; + +/** + * Created by Oliver on 05/07/2017. + */ +public class ArrayExample { + public static void main(String[] args) { + /* 数组排序及元素查找 */ + sort_search(); + + /* 数组添加元素 */ + int[] array = {1, 2, 4}; + insertElement(array, 3, 2); + + /**数组反转 + * asList方法返回一个受指定数组支持的固定大小的列表, + * 此方法同 Collection.toArray 一起,充当了基于数组的 API 与基于 collection 的 API 之间的桥梁 + */ + List list = Arrays.asList(1, 3, 2); + reverse(new ArrayList(list)); + + /* 数组获取最大和最小值 */ + max_min(); + + /* 数组合并 */ + String[] strings1 = {"a", "b"}; + String[] strings2 = {"c", "d"}; + concatenate(strings1, strings2); + + /* 数组填充 */ + fill(); + + /* 数组扩容 */ + extend(strings1, strings2); + + /* 删除数组元素 */ + String[] strings3 = {"a", "b", "c"}; + remove(strings3, "b"); + + /* 数组差集 */ + String[] strings4 = {"a", "b", "c"}; + String[] strings5 = {"a", "d", "e"}; + uncommon(strings4, strings5); + + /* 数组交集 */ + common(strings4, strings5); + + /* 在数组中查找指定元素 */ + contain(strings4, "c"); + contain(strings4, strings5); + contain(strings4, strings1); + + /* 判断数组是否相等 */ + String[] strings6 = {"a", "b", "c"}; + String[] strings7 = {"a", "c", "b"}; + equal(strings4, strings6); + equal(strings7, strings6); + + /* 数组并集 */ + union(strings4, strings5); + + } + + public static void printArray(String message, int[] array) { + System.out.println(message + "length: " + array.length); + for (int i : array) { + System.out.print(i); + System.out.print(", "); + } + System.out.println(); + } + + public static void printArray(String message, String[] array) { + System.out.println(message + "length: " + array.length); + for (String i : array) { + System.out.print(i); + System.out.print(", "); + } + System.out.println(); + } + + public static void sort_search() { + int[] array = {-1, 0, -2, 7, 10, 9}; + Arrays.sort(array); + printArray("sort_search ", array); + int index = Arrays.binarySearch(array, 7); + System.out.println("元素7的索引值(负数为不存在): " + index); + } + + public static void insertElement(int[] origin, int element, int index) { + int length = origin.length; + int[] destination = new int[length + 1]; + System.arraycopy(origin, 0, destination, 0, index); + destination[index] = element; + System.arraycopy(origin, index, destination, index + 1, length - index); + printArray("insertElement", destination); + } + + public static void reverse(ArrayList arrayList) { + System.out.println("\n反转前排序: " + arrayList.toString()); + Collections.reverse(arrayList); + System.out.println("\n反转后排序: " + arrayList.toString()); + } + + public static void max_min() { + Integer[] numbers = {1, 5, 7, 10}; + System.out.println("Max: " + Collections.max(Arrays.asList(numbers))); + System.out.println("Min: " + Collections.min(Arrays.asList(numbers))); + } + + public static void concatenate(String[] s1, String[] s2) { + List list1 = new ArrayList(Arrays.asList(s1)); + List list2 = new ArrayList(Arrays.asList(s2)); + list1.addAll(list2); + System.out.println("Concatenated: " + list1); + } + + public static void fill() { + int[] array = new int[6]; + Arrays.fill(array, 100); + printArray("fill 100 ", array); + + Arrays.fill(array, 3, 6, 50); + printArray("fill 100 50 ", array); + } + + public static void extend(String[] origin, String[] extend) { + String[] destination = new String[origin.length + extend.length]; + System.arraycopy(origin, 0, destination, 0, origin.length); + System.arraycopy(extend, 0, destination, origin.length, extend.length); + printArray("extend ", destination); + } + + public static void remove(String[] origin, String element) { + List list = new ArrayList<>(Arrays.asList(origin)); + list.remove(element); + System.out.printf("remove %s from %s: %s%n", element, origin, list); + } + + public static void uncommon(String[] strings1, String[] strings2) { + ArrayList arrayList1 = new ArrayList(Arrays.asList(strings1)); + ArrayList arrayList2 = new ArrayList(Arrays.asList(strings2)); + arrayList1.removeAll(arrayList2); + System.out.println("uncommon: " + arrayList1); + } + + public static void common(String[] strings1, String[] strings2) { + ArrayList arrayList1 = new ArrayList(Arrays.asList(strings1)); + ArrayList arrayList2 = new ArrayList(Arrays.asList(strings2)); + arrayList1.retainAll(arrayList2); + System.out.println("common: " + arrayList1); + } + + public static void contain(String[] strings1, String element) { + ArrayList arrayList1 = new ArrayList(Arrays.asList(strings1)); + System.out.printf("%s contains %s: %s%n", arrayList1, element, arrayList1.contains(element)); + } + + public static void contain(String[] strings1, String[] strings2) { + ArrayList arrayList1 = new ArrayList(Arrays.asList(strings1)); + ArrayList arrayList2 = new ArrayList(Arrays.asList(strings2)); + System.out.printf("%s contains %s: %s%n", arrayList1, arrayList2, arrayList1.contains(arrayList2)); + } + + public static void equal(String[] strings1, String[] strings2) { + System.out.printf("%s equals %s: %s%n", strings1, strings2, Arrays.equals(strings1, strings2)); + } + + public static void union(String[] strings1, String[] strings2) { + /* + 求两个字符串数组的并集,利用set的元素唯一性 + */ + Set stringSet = new HashSet<>(); + for (String s : strings1) { + stringSet.add(s); + } + for (String s : strings2) { + stringSet.add(s); + } + System.out.println("union: " + stringSet); + } +} diff --git a/src/tutorial/examples/StringExample.java b/src/tutorial/examples/StringExample.java new file mode 100644 index 0000000..648a8cc --- /dev/null +++ b/src/tutorial/examples/StringExample.java @@ -0,0 +1,115 @@ +package examples; + +import java.util.Locale; + +/** + * Created by Oliver on 05/07/2017. + */ +public class StringExample { + public static void main(String[] args) { + /* 删除字符串中的一个字符 */ + System.out.println(removeCharAt("Google", 2)); + + /* 字符串替换 */ + replace(); + + /* 字符串反转 */ + System.out.println(reverse("Java")); + + /* 字符串搜索 */ + System.out.println(search("Java", "v")); + + /* 字符串分割 */ + split("1,2,3", ","); + + /* 字符串大小写转换 */ + upper_lower("Java", 1); + upper_lower("Java", 2); + + /* 测试两个字符串区域是否相等 */ + regionMatches(); + + /* 字符串性能比较测试 */ + comparePerformance(); + + /* 字符串格式化 */ + format(); + + } + + + public static String removeCharAt(String s, Integer index) { + return s.substring(0, index) + s.substring(index + 1); + } + + public static void replace() { + String str = "Hello World"; + System.out.println(str.replace('H', 'W')); + System.out.println(str.replaceFirst("He", "Wa")); + System.out.println(str.replaceAll("He", "Ha")); + } + + public static String reverse(String s) { + StringBuffer stringBuffer = new StringBuffer(s); + String reversed = stringBuffer.reverse().toString(); + return reversed; + } + + public static Integer search(String s, String match) { + return s.indexOf(match); + } + + public static void split(String s, String delimiter, Integer... limit) { + for (String string : s.split(delimiter, limit[0])) { + System.out.println(string); + } + } + + public static void split(String s, String delimiter) { + split(s, delimiter, 0); + } + + public static void upper_lower(String s, int uplow) { + String changed = ""; + switch (uplow) { + case 1: + changed = s.toUpperCase(); + break; + case 2: + changed = s.toLowerCase(); + break; + } + System.out.println(changed); + } + + public static void regionMatches() { + String s1 = "Java is best"; + String s2 = "Best is java"; + boolean matches1 = s1.regionMatches(0, "Java", 0, 4); + boolean matches2 = s2.regionMatches(true, 8, "Java", 0, 4); + System.out.println(matches1); + System.out.println(matches2); + } + + public static void comparePerformance() { + long st1 = System.currentTimeMillis(); + for (int i = 0; i < 50000; i++) { + String s1 = "java"; + } + long et1 = System.currentTimeMillis(); + System.out.println("Duration1: " + (et1 - st1)); + + long st2 = System.currentTimeMillis(); + for (int i = 0; i < 50000; i++) { + String s2 = new String("java"); + } + long et2 = System.currentTimeMillis(); + System.out.println("Duration2: " + (et2 - st2)); + } + + public static void format() { + System.out.format("Math.E: %f%n", Math.E); + System.out.format(Locale.CHINA, "Math.E: %.4f%n", Math.E); //指定本地为中国(CHINA) + } + +} From 5304f91c8d14b3b05273973187b695b663a4574a Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Thu, 6 Jul 2017 15:39:46 +0800 Subject: [PATCH 30/41] Date --- src/tutorial/examples/DateExample.java | 45 ++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/tutorial/examples/DateExample.java diff --git a/src/tutorial/examples/DateExample.java b/src/tutorial/examples/DateExample.java new file mode 100644 index 0000000..2c86f10 --- /dev/null +++ b/src/tutorial/examples/DateExample.java @@ -0,0 +1,45 @@ +package examples; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +/** + * Created by Oliver on 06/07/2017. + */ +public class DateExample { + public static void main(String[] args) { + /* 格式化时间 */ + /* 时间戳转换成时间 */ + SimpleDateFormat(); + + /* 获取年份、月份等 */ + Calendar(); + } + + public static void SimpleDateFormat() { + Date date = new Date(); + Long timestamp = System.currentTimeMillis(); //获取当前时间戳 + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a zzz"); + System.out.println(simpleDateFormat.format(date)); + + // 时间戳转换成时间 + String sd = simpleDateFormat.format(new Date(Long.parseLong(String.valueOf(timestamp)))); + System.out.println(sd); + } + + public static void Calendar() { + Calendar calendar = Calendar.getInstance(); + System.out.println("calendar.YEAR: " + calendar.get(Calendar.YEAR)); + System.out.println("calendar.MONTH: " + calendar.get(Calendar.MONTH)); + System.out.println("calendar.WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR)); + System.out.println("calendar.WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH)); + System.out.println("calendar.DATE: " + calendar.get(Calendar.DATE)); + System.out.println("calendar.DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR)); + System.out.println("calendar.DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK)); + System.out.println("calendar.DAY_OF_WEEK_IN_MONTH: " + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH)); + System.out.println("calendar.DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH)); + } + + +} From ccb15837d59517add296afade6b40201edaed387 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Sat, 8 Jul 2017 20:14:54 +0800 Subject: [PATCH 31/41] Collections --- .../{ArrayExample.java => ArraysExample.java} | 2 +- src/tutorial/examples/CollectionsExample.java | 305 ++++++++++++++++++ src/tutorial/examples/DataExample.java | 182 +++++++++++ 3 files changed, 488 insertions(+), 1 deletion(-) rename src/tutorial/examples/{ArrayExample.java => ArraysExample.java} (99%) create mode 100644 src/tutorial/examples/CollectionsExample.java create mode 100644 src/tutorial/examples/DataExample.java diff --git a/src/tutorial/examples/ArrayExample.java b/src/tutorial/examples/ArraysExample.java similarity index 99% rename from src/tutorial/examples/ArrayExample.java rename to src/tutorial/examples/ArraysExample.java index 5ed04b8..151115c 100644 --- a/src/tutorial/examples/ArrayExample.java +++ b/src/tutorial/examples/ArraysExample.java @@ -5,7 +5,7 @@ /** * Created by Oliver on 05/07/2017. */ -public class ArrayExample { +public class ArraysExample { public static void main(String[] args) { /* 数组排序及元素查找 */ sort_search(); diff --git a/src/tutorial/examples/CollectionsExample.java b/src/tutorial/examples/CollectionsExample.java new file mode 100644 index 0000000..fe50a03 --- /dev/null +++ b/src/tutorial/examples/CollectionsExample.java @@ -0,0 +1,305 @@ +package examples; + +import java.util.*; + +/** + * Created by Oliver on 08/07/2017. + */ +public class CollectionsExample { + public static void main(String[] args) { + /* 数组转集合 */ + asList(); + + /* 集合比较 */ + max_min(); + + /* 使用 Collection 类的 iterator() 方法来遍历集合 */ + iterator(); + + /* 集合长度 */ + size(); + + /* 集合打乱顺序 */ + shuffle(); + + /* 使用普通for,增强型的 for ,iterator 等方式来遍历list */ + traverse_list(); + + /* 使用增强型的 for ,iterator 等方式来遍历set */ + traverse_set(); + + /* Map类型集合的遍历 */ + traverse_map(); + + /* 集合反转 */ + reverse(); + + /* 删除集合中指定元素 */ + remove(); + + /* 只读集合 */ + unmodifiableList(); + + /* 集合输出 */ + mapOutput(); + + /* list.add() 和 list.toArray() 方法将集合转为数组 */ + collectionsToArrays(); + + /* List 循环移动元素 */ + rotate(); + + /* 遍历 HashTable 的键值 */ + hashtableKeys(); + + /* List 元素替换 */ + replace(); + + /* List 截取 */ + indexOfSubList(); + } + + public static void asList() { + String[] s = new String[5]; + for (int i = 0; i < 5; i++) { + s[i] = String.valueOf(i); + System.out.print(s[i] + ", "); + } + List list = new ArrayList(Arrays.asList(s)); + System.out.println("\nArrays.toList: " + list); + } + + public static void max_min() { + String[] coins = {"Penny", "nickel", "dime", "Quarter", "dollar"}; + TreeSet set = new TreeSet(); + for (String coin : coins) { + set.add(coin); + } + System.out.println("TreeSet: " + set); + System.out.println("Max: " + Collections.max(set)); + System.out.println("Min: " + Collections.min(set, String.CASE_INSENSITIVE_ORDER)); + } + + public static void iterator() { + HashMap hashMap = new HashMap(); + hashMap.put("1", "1st"); + hashMap.put("2", "2nd"); + hashMap.put("3", "3rd"); + Collection c = hashMap.values(); + Iterator it = c.iterator(); + while (it.hasNext()) { + System.out.println(it.next()); + } + } + + public static void size() { + HashSet hashSet = new HashSet(); + if (hashSet.isEmpty()) { + System.out.println("HashSet是空的"); + } + hashSet.add("a"); + hashSet.add("b"); + hashSet.add("c"); + System.out.println("HashSet size: " + hashSet.size()); + } + + public static void shuffle() { + List list = new ArrayList(); + for (int i = 0; i < 10; i++) { + list.add(i); + } + System.out.println("Before shuffle: " + list); + Collections.shuffle(list); + System.out.println("After shuffle: " + list); + } + + public static void traverse_list() { + List list = new ArrayList(); + list.add("a"); + list.add("b"); + list.add("c"); + // 使用传统for循环进行遍历 + for (int i = 0; i < list.size(); i++) { + System.out.print(list.get(i) + ", "); + } + System.out.println(); + + // 使用增强for循环进行遍历 + for (String s : list) { + System.out.print(String.valueOf(s) + ", "); + } + System.out.println(); + + // 使用iterator遍历 + Iterator iterator = list.iterator(); + while (iterator.hasNext()) { + System.out.print(iterator.next() + ", "); + } + System.out.println(); + } + + public static void traverse_set() { + HashSet hashSet = new HashSet(); + hashSet.add("A"); + hashSet.add("B"); + hashSet.add("C"); + hashSet.add("A"); + + // 使用增强for循环进行遍历 + for (String s : hashSet) { + System.out.print(s + ", "); + } + System.out.println(); + + // 使用iterator遍历 + Iterator iterator = hashSet.iterator(); + while (iterator.hasNext()) { + System.out.print(iterator.next() + ", "); + } + System.out.println(); + } + + public static void traverse_map() { + HashMap hashMap = new HashMap(); + hashMap.put("1", "1st"); + hashMap.put("2", "2nd"); + hashMap.put("3", "3rd"); + + // 使用entrySet()方法,获取maps集合中的每一个键值对, + for (Map.Entry s : hashMap.entrySet()) { + System.out.println(s.getKey() + ":" + s.getValue()); + } + + for (String s : hashMap.values()) { + System.out.print(s + ", "); + } + System.out.println(); + + // 使用keySet()方法,获取maps集合中的所有键,遍历键取得所对应的值。 + for (String s : hashMap.keySet()) { + System.out.print(s + ":" + hashMap.get(s) + ", "); + } + System.out.println(); + + // 取得迭代器遍历出对应的值。 + Iterator iterator = hashMap.entrySet().iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); + } + } + + public static void reverse() { + String[] coins = {"A", "B", "C", "D", "E"}; + List list = new ArrayList<>(Arrays.asList(coins)); + System.out.println("list before reverse: " + list); + Collections.reverse(list); + ListIterator iterator = list.listIterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); + } + } + + public static void remove() { + HashSet hashSet = new HashSet(); + hashSet.add("a"); + hashSet.add("1"); + hashSet.add("b"); + System.out.println("HashSet before removal:" + hashSet); + + hashSet.remove("1"); + Iterator iterator = hashSet.iterator(); + while (iterator.hasNext()) { + System.out.print(iterator.next() + ", "); + } + System.out.println(); + } + + public static void unmodifiableList() { + List stuff = new ArrayList(Arrays.asList(new String[]{"a", "b"})); + System.out.println("Original list: " + stuff); + stuff.add("c"); + System.out.println("Add c to list: " + stuff); + + // 使用 Collection 类的 Collections.unmodifiableList() 方法来设置集合为只读 + stuff = Collections.unmodifiableList(stuff); + try { + stuff.add("d"); + } catch (UnsupportedOperationException u) { + System.out.println("List is set to unmodifiableList"); + } + System.out.println("Add d to list: " + stuff); + } + + public static void mapOutput() { + // 使用 Java Util 类的 tMap.keySet(),tMap.values() 和 tMap.firstKey() 方法将集合元素输出 + TreeMap tMap = new TreeMap(); + tMap.put(0, "Sunday"); + tMap.put(1, "Monday"); + tMap.put(2, "Tuesday"); + tMap.put(3, "Wednesday"); + tMap.put(4, "Thursday"); + tMap.put(5, "Friday"); + tMap.put(6, "Saturday"); + System.out.println("TreeMap keySet: " + tMap.keySet()); + System.out.println("TreeMap values: " + tMap.values()); + System.out.println("TreeMap firstEntry: " + tMap.firstEntry()); + System.out.println("TreeMap firstKey: " + tMap.firstKey()); + System.out.println("TreeMap lastKey: " + tMap.lastKey()); + tMap.remove(tMap.firstKey()); + tMap.remove(tMap.lastKey()); + System.out.println("TreeMap firstEntry: " + tMap.firstEntry()); + System.out.println("TreeMap lastEntry: " + tMap.lastEntry()); + } + + public static void collectionsToArrays() { + List list = new ArrayList<>(); + list.add("J"); + list.add("a"); + list.add("v"); + list.add("a"); + System.out.println("List: " + list); + String[] array = list.toArray(new String[0]); + for (int i = 0; i < array.length; i++) { + System.out.print(array[i] + ", "); + } + System.out.println(); + } + + public static void rotate() { + String[] arr = "I do love java".split(" "); + List list = new ArrayList<>(Arrays.asList(arr)); + System.out.println("Before rotate: " + list); + Collections.rotate(list, 2); + System.out.println("After rotate: " + list); + } + + public static void hashtableKeys() { + Hashtable hashtable = new Hashtable<>(); + hashtable.put(1, "first"); + hashtable.put(2, "second"); + hashtable.put(3, "third"); + Enumeration keys = hashtable.keys(); + while (keys.hasMoreElements()) { + Object key = keys.nextElement(); + System.out.println(String.valueOf(key) + ":" + hashtable.get(key)); + } + } + + public static void replace() { + String[] strings = "Python,Java,Ruby,Go,Java,Python".split(","); + List list = new ArrayList<>(Arrays.asList(strings)); + System.out.println("Before replace: " + list); + Collections.replaceAll(list, "Python", "Py"); + System.out.println("After replace: " + list); + } + + public static void indexOfSubList() { + // 使用 Collections 类的 indexOfSubList() 和 lastIndexOfSubList() 方法来查看子列表是否在列表中,并查看子列表在列表中所在的位置 + List list = Arrays.asList("Python,Java,Ruby,Go,Java,Ruby,Python".split(",")); + System.out.println(list); + List subList = Arrays.asList("Java Ruby".split(" ")); + System.out.println(subList); + System.out.println("IndexOfSubList: " + Collections.indexOfSubList(list, subList)); + System.out.println("LastIndexOfSubList: " + Collections.lastIndexOfSubList(list, subList)); + } +} diff --git a/src/tutorial/examples/DataExample.java b/src/tutorial/examples/DataExample.java new file mode 100644 index 0000000..2868aa2 --- /dev/null +++ b/src/tutorial/examples/DataExample.java @@ -0,0 +1,182 @@ +package examples; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.Queue; +import java.util.Vector; + +/** + * Created by Oliver on 06/07/2017. + */ +public class DataExample { + private static int index = 0; + private static long[] longArray = new long[10]; + + public static void main(String[] args) { + /* 数字求和运算 */ + System.out.println(sum(100)); + + /* 在链表(LinkedList)的开头和结尾添加元素 */ + /* 获取链表(LinkedList)的第一个和最后一个元素 */ + first_last(); + + /* 删除链表中的元素 */ + remove(); + + /* 获取向量元素的索引值 */ + sort(); + + /* 栈的实现 */ + push(100); + push(200); + push(300); + push(400); + push(500); + pop(); + pop(); + pop(); + pop(); + pop(); + + /* 链表元素查找 */ + indexOf(); + + /* 队列(Queue)用法 */ + queue(); + + /* 获取向量的最大元素 */ + max(); + + /* 链表修改 */ + set(); + + /* 交换向量 */ + swap(); + + } + + public static int sum(int count) { + int current = 0; + int sum = 0; + do { + sum = current + sum; + current++; + } while (current <= count); + return sum; + } + + public static void first_last() { + LinkedList linkedList = new LinkedList(); + linkedList.add("1"); + linkedList.add("2"); + linkedList.addFirst("0"); + linkedList.addLast("3"); + System.out.println("LinkedList: " + linkedList); + System.out.println("LinkedList getFirst: " + linkedList.getFirst()); + System.out.println("LinkedList getLast: " + linkedList.getLast()); + } + + public static void remove() { + LinkedList linkedList = new LinkedList(); + linkedList.add("1"); + linkedList.add("2"); + linkedList.add("3"); + linkedList.add("4"); + System.out.println("LinkedList: " + linkedList); + linkedList.subList(1, 3).clear(); + System.out.println("LinkedList after removal: " + linkedList); + + } + + public static void sort() { + Vector vector = new Vector(); + vector.add("4"); + vector.add("2"); + vector.add("1"); + vector.add("3"); + System.out.println("Vector: " + vector); + int index1 = Collections.binarySearch(vector, "3"); + System.out.println("Index of 3: " + index1); + + Collections.sort(vector); + System.out.println("Vector sort: " + vector); + + int index2 = Collections.binarySearch(vector, "3"); + System.out.println("Index of 3: " + index2); + } + + public static void printArray(long[] longs) { + for (long l : longs) { + System.out.print(l); + System.out.print(", "); + } + System.out.println(); + } + + public static void push(long l) { + longArray[index++] = l; + printArray(longArray); + } + + public static void pop() { + long top = longArray[--index]; + System.out.printf("%d is popped%n", top); + } + + public static void indexOf() { + LinkedList linkedList = new LinkedList(); + linkedList.add("A"); + linkedList.add("B"); + linkedList.add("C"); + linkedList.add("D"); + System.out.println("LinkedList: " + linkedList); + System.out.println("LinkedList index of C: " + linkedList.indexOf("C")); + System.out.println("LinkedList index of B: " + Collections.binarySearch(linkedList, "B")); + } + + public static void queue() { + //add()和remove()方法在失败的时候会抛出异常(不推荐) + Queue queue = new LinkedList(); + queue.offer("a"); + queue.offer("b"); + queue.offer("c"); + System.out.println("queue: " + queue); + System.out.println("queue.poll返回第一个元素,并在队列中删除: " + queue.poll()); + System.out.println("queue: " + queue); + System.out.println("queue.element返回第一个元素: " + queue.element()); + System.out.println("queue: " + queue); + System.out.println("queue.peek返回第一个元素: " + queue.peek()); + System.out.println("queue: " + queue); + } + + public static void max() { + Vector v = new Vector(); + v.add(new Double("3.14")); + v.add(new Double("3.141")); + v.add(new Double("3.1")); + System.out.println("Vector.max: " + Collections.max(v)); + } + + public static void set() { + LinkedList linkedList = new LinkedList(); + linkedList.add("a"); + linkedList.add("x"); + linkedList.add("c"); + System.out.println("LinkedList: " + linkedList); + linkedList.set(1, "b"); + System.out.println("LinkedList: " + linkedList); + } + + public static void swap() { + Vector v = new Vector(); + v.add("1"); + v.add("4"); + v.add("3"); + v.add("2"); + v.add("5"); + System.out.println("Vector before swap: " + v); + Collections.swap(v, 1, 3); + System.out.println("Vector after swap: " + v); + } + +} From 1f0efff071c1133c49ad68f8446cb1fc5ede1d4d Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Sun, 9 Jul 2017 17:46:32 +0800 Subject: [PATCH 32/41] method --- src/tutorial/examples/MethodExample.java | 142 +++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 src/tutorial/examples/MethodExample.java diff --git a/src/tutorial/examples/MethodExample.java b/src/tutorial/examples/MethodExample.java new file mode 100644 index 0000000..151b983 --- /dev/null +++ b/src/tutorial/examples/MethodExample.java @@ -0,0 +1,142 @@ +package examples; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Oliver on 08/07/2017. + */ +public class MethodExample { + public static void main(String[] args) { + /* 斐波那契数列 */ + System.out.println("fibonacci: " + fibonacci(2)); + + /* 阶乘 */ + System.out.println("factorial: " + factorial(5)); + + /* instanceOf 关键字用法 */ + instanceOf(3.14f); + instanceOf("String"); + + /* continue 关键字用法 */ + continues(); + + /* enum 和 switch 语句使用 */ + Language language = Language.Java; + enum_switch(language); + + /* Enum(枚举)构造函数及方法的使用 */ + try_enum(); + + /* Varargs 可变参数使用 */ + int[] intArrays = {1, 3, 5}; + System.out.println("Sum of variable args: " + varargs(intArrays)); + + /* 重载(overloading)方法中使用 Varargs */ + double[] doubleArrays = {1.1, 2.2, 3.3}; + System.out.println("Sum of variable args: " + varargs(doubleArrays)); + } + + public static List fibonacci(long count) { + List list = new ArrayList<>(); + if (count <= 1) { + list.add(0l); + return list; + } else { + list.add(0l); + list.add(1l); + long next; + for (int i = 2; i < count; i++) { + next = list.get(i - 2) + list.get(i - 1); + list.add(next); + } + } + return list; + } + + public static long factorial(long num) { + long result = 1; + if (num > 1) { + for (int i = 1; i <= num; i++) { + result = result * i; + } + } + return result; + } + + public static void instanceOf(Object o) { + if (o instanceof Integer) { + System.out.println("Object is instanceOf Integer"); + } else if (o instanceof Float) { + System.out.println("Object is instanceOf Float"); + } else if (o instanceof String) { + System.out.println("Object is instanceOf String"); + } + } + + public static void continues() { + StringBuffer searchstr = new StringBuffer("hello how are you. "); + int found = 0; + for (int i = 0; i < searchstr.length(); i++) { + if (searchstr.charAt(i) == 'h') { + found++; + continue; + } + } + System.out.printf("%d 'h' found in 'hello how are you. '%n", found); + } + + enum Language { + Java(1), Python(2), Go(3), Javascript(4); + private int id; + + Language(int id) { + this.id = id; + } + + public int getId() { + return this.id; + } + } + + public static void enum_switch(Language language) { + switch (language) { + case Java: + System.out.println("Language: Java"); + break; + case Python: + System.out.println("Language: Python"); + break; + case Go: + System.out.println("Language: Go"); + break; + case Javascript: + System.out.println("Language: Javascript"); + break; + } + } + + public static void try_enum() { + for (Language l : Language.values()) { + System.out.printf("%s: %d", l, l.getId()); + System.out.println(); + } + } + + public static int varargs(int... varargs) { + int sum = 0; + for (int i = 0; i < varargs.length; i++) { + sum += varargs[i]; + } + return sum; + } + + public static double varargs(double... varargs) { + double sum = 0; + for (double d : varargs) { + sum += d; + } + return sum; + } +} + From ccb94060b08db1fd19ecf2fdb491128b3730cf9e Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Mon, 10 Jul 2017 15:51:00 +0800 Subject: [PATCH 33/41] File --- src/tutorial/examples/FileExample.java | 208 +++++++++++++++++++++++++ src/tutorial/examples/new.txt | 0 src/tutorial/examples/rename.txt | 1 + 3 files changed, 209 insertions(+) create mode 100644 src/tutorial/examples/FileExample.java create mode 100644 src/tutorial/examples/new.txt create mode 100644 src/tutorial/examples/rename.txt diff --git a/src/tutorial/examples/FileExample.java b/src/tutorial/examples/FileExample.java new file mode 100644 index 0000000..7e27c09 --- /dev/null +++ b/src/tutorial/examples/FileExample.java @@ -0,0 +1,208 @@ +package examples; + +import java.io.*; +import java.util.Date; + +/** + * Created by Oliver on 09/07/2017. + */ +public class FileExample { + public static void main(String[] args) { + + File dir = new File("src/tutorial/examples"); + File file = new File(dir.getPath() + File.separator + "file.txt"); + File copy = new File(dir.getPath() + File.separator + "copy.txt"); + File rename = new File(dir.getPath() + File.separator + "rename.txt"); + File newFile = new File(dir.getPath() + File.separator + "new.txt"); + + /* 使用 write() 方法向文件写入内容 */ + bufferedWriter(); + + /* 使用 readLine() 方法来读取文件内容 */ + bufferedReader(); + + /* 使用 BufferedWriter 类的 read 和 write 方法将文件内容复制到另一个文件 */ + + copy(file, copy); + + /* 使用 FileWriter 方法向文件中追加数据 */ + append(); + + /* 使用 File 类的 createTempFile() 方法来创建临时文件 */ + tmpFile(dir); + + /* 使用 File 类的 fileToChange.lastModified() 和 fileToChange setLastModified() 方法来修改文件最后的修改日期 */ + fileToChange(copy); + + /* 使用 File 类的 file.exists() 和 file.length() 方法来获取文件大小,以字节计算(1KB=1024字节 ) */ + length(file); + length(copy); + + /* 使用 File 类的 oldName.renameTo(newName) 方法来重命名文件 */ + rename(copy, rename); + + /* 使用 File 类的 file.setReadOnly() 和 file.canWrite() 方法来设置文件只读 */ + readOnly(rename); + + /* 使用 File 类的 File() 构造函数和 file.createNewFile() 方法来创建一个新的文件 */ + newFile(newFile); + newFile(rename); + + /* 使用 File 类的 filename.compareTo (another filename) 方法来比较两个文件路径是否在同一个目录下 */ + compareTo(newFile, rename); + compareTo(newFile, newFile); + + /* 删除文件 */ + delete(file); + + + } + + public static void bufferedWriter() { + try { + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("src/tutorial/examples/file.txt")); + bufferedWriter.write("1. Java File Examples\n"); + bufferedWriter.close(); + System.out.println("文件创建成功!"); + } catch (IOException i) { + i.printStackTrace(); + } + } + + public static void bufferedReader() { + try { + BufferedReader bufferedReader = new BufferedReader(new FileReader("src/tutorial/examples/file.txt")); + String line; + while ((line = bufferedReader.readLine()) != null) { + System.out.println(line); + } + } catch (IOException i) { + i.printStackTrace(); + } + } + + public static void delete(File file) { + try { + if (file.delete()) { + System.out.println(file.getName() + " 文件已被删除!"); + } else { + System.out.println("文件删除失败!"); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void copy(File from, File to) { + try { + InputStream inputStream = new FileInputStream(from); + OutputStream outputStream = new FileOutputStream(to); + + byte[] bytes = new byte[1024]; + int len; + while ((len = inputStream.read(bytes)) > 0) { + outputStream.write(bytes, 0, len); + } + inputStream.close(); + outputStream.close(); + + BufferedReader bufferedReader = new BufferedReader(new FileReader("src/tutorial/examples/copy.txt")); + String line; + while ((line = bufferedReader.readLine()) != null) { + System.out.println("BufferedReader readLine: " + line); + } + bufferedReader.close(); + } catch (FileNotFoundException f) { + f.printStackTrace(); + } catch (IOException i) { + i.printStackTrace(); + } + } + + public static void append() { + try { + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("src/tutorial/examples/file.txt", true)); + bufferedWriter.write("2. Append content to file"); + bufferedWriter.close(); + + BufferedReader bufferedReader = new BufferedReader(new FileReader("src/tutorial/examples/file.txt")); + String line; + while ((line = bufferedReader.readLine()) != null) { + System.out.println(line); + } + bufferedReader.close(); + } catch (FileNotFoundException f) { + f.printStackTrace(); + } catch (IOException i) { + i.printStackTrace(); + } + } + + public static void tmpFile(File dir) { + try { + File tmpFile = File.createTempFile("pattern", ".suffix", dir); + tmpFile.deleteOnExit(); + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tmpFile)); + bufferedWriter.write("temp string"); + System.out.println("临时文件已创建: " + tmpFile.getName()); + bufferedWriter.close(); + } catch (IOException i) { + i.printStackTrace(); + } + } + + public static void fileToChange(File file) { + Date time1 = new Date(file.lastModified()); + System.out.println("lastModified1: " + time1); + try { + Thread.sleep(3000); + } catch (InterruptedException i) { + i.printStackTrace(); + } + file.setLastModified(new Date().getTime()); + Date time2 = new Date(file.lastModified()); + System.out.println("lastModified2: " + time2); + } + + public static void length(File file) { + if (file.exists()) { + System.out.println("file.length: " + file.length()); + } + } + + public static void rename(File file, File rename) { + try { + file.renameTo(rename); + System.out.printf("%s已重命名: %s%n", file.getName(), rename.getName()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void readOnly(File file) { + System.out.printf("%s can be written: %s%n", file.getName(), file.canWrite()); + file.setReadOnly(); + System.out.printf("%s can be written: %s%n", file.getName(), file.canWrite()); + } + + public static void newFile(File file) { + try { + if (file.createNewFile()) { + System.out.println("New file created: " + file.getName()); + } else { + System.out.printf("File %s already existed!%n", file.getName()); + } + } catch (IOException i) { + i.printStackTrace(); + } + } + + public static void compareTo(File f1, File f2) { + int i = f1.compareTo(f2); + if (i == 0) { + System.out.printf("%s and %s share the file path%n", f1, f2); + } else { + System.out.printf("%s and %s have different file path%n", f1, f2); + } + } +} diff --git a/src/tutorial/examples/new.txt b/src/tutorial/examples/new.txt new file mode 100644 index 0000000..e69de29 diff --git a/src/tutorial/examples/rename.txt b/src/tutorial/examples/rename.txt new file mode 100644 index 0000000..51eec85 --- /dev/null +++ b/src/tutorial/examples/rename.txt @@ -0,0 +1 @@ +1. Java File Examples From 787675819eafc5d810db4deda84fef1d7698600e Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Tue, 11 Jul 2017 18:24:07 +0800 Subject: [PATCH 34/41] network, socket --- src/tutorial/IO.java | 1 + src/tutorial/examples/Client.java | 38 +++++ src/tutorial/examples/NetworkExample.java | 174 ++++++++++++++++++++++ src/tutorial/examples/Server.java | 37 +++++ src/tutorial/examples/output.html | 2 + src/tutorial/file/Files.java | 1 + 6 files changed, 253 insertions(+) create mode 100644 src/tutorial/examples/Client.java create mode 100644 src/tutorial/examples/NetworkExample.java create mode 100644 src/tutorial/examples/Server.java create mode 100644 src/tutorial/examples/output.html diff --git a/src/tutorial/IO.java b/src/tutorial/IO.java index 36bb235..15da412 100644 --- a/src/tutorial/IO.java +++ b/src/tutorial/IO.java @@ -10,6 +10,7 @@ public static void IO_BufferedReader() throws IOException { // 把 System.in 包装在一个 BufferedReader 对象中来创建一个字符流 char c; String s; + // InputStreamReader:是字节流通往字符流的桥梁,使用指定的charset读取字节并解码成字符 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Input character, 'q' to exit"); // 使用 BufferedReader 在控制台读取字符 diff --git a/src/tutorial/examples/Client.java b/src/tutorial/examples/Client.java new file mode 100644 index 0000000..e4b7060 --- /dev/null +++ b/src/tutorial/examples/Client.java @@ -0,0 +1,38 @@ +package examples; + +import java.io.*; +import java.net.Socket; + +/** + * Created by Oliver on 11/07/2017. + */ +public class Client { + /** + * 建立客户端 + * 创建Socket通信,设置通信服务器的IP和Port + * 建立IO输出流向服务器发送数据消息 + * 建立IO输入流读取服务器发送来的数据消息 + */ + public static void main(String[] args) { + try { + Socket socket = new Socket("127.0.0.1", 8888); + + //构建IO + InputStream inputStream = socket.getInputStream(); + OutputStream outputStream = socket.getOutputStream(); + + //向服务器端发送一条消息 + BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream)); + bufferedWriter.write("测试客户端和服务器通信,服务器接收到消息返回到客户端\n"); + bufferedWriter.flush(); + + //读取服务器返回的消息 + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + String msg = bufferedReader.readLine(); + System.out.println("服务器: " + msg); + + } catch (IOException i) { + i.printStackTrace(); + } + } +} diff --git a/src/tutorial/examples/NetworkExample.java b/src/tutorial/examples/NetworkExample.java new file mode 100644 index 0000000..1b935dc --- /dev/null +++ b/src/tutorial/examples/NetworkExample.java @@ -0,0 +1,174 @@ +package examples; + +import java.io.*; +import java.net.*; +import java.util.Date; +import java.util.List; +import java.util.Map; + +/** + * Created by Oliver on 10/07/2017. + */ +public class NetworkExample { + public static void main(String[] args) { + + File output = new File("src/tutorial/examples/output.html"); + + /* 获取指定主机的IP地址 */ + InetAddress("www.jd.com"); + + /* 查看端口是否已使用 */ + socketPort("127.0.0.1"); + + /* 获取本机ip地址及主机名 */ + InetAddress_localhost(); + + /* 获取远程文件大小 */ + getContentLength("http://www.runoob.com/wp-content/themes/runoob/assets/img/newlogo.png"); + + /* 使用 net.Socket 类的 getInetAddress() 方法来连接到指定主机 */ + getInetAddress("www.jd.com"); + + /* 使用 net.URL 类的 URL() 构造函数来抓取网页 */ + url_openStream("http://www.baidu.com", output); + + /* 获取 URL 响应头信息 */ + URLConnection_getDate("http://www.jd.com"); + + /* 获取 URL 响应头信息 */ + URLConnection_getHeaderFields("http://www.jd.com"); + + /* 解析 URL */ + url_info("http://www.runoob.com/html/html-tutorial.html"); + + } + + public static void InetAddress(String hostName) { + InetAddress inetAddress = null; + try { + inetAddress = InetAddress.getByName(hostName); + + } catch (UnknownHostException u) { + System.exit(2); + } + System.out.println(inetAddress.getHostName() + ": " + inetAddress.getHostAddress()); + } + + public static void socketPort(String host) { + Socket Skt; + for (int i = 8000; i < 8100; i++) { + try { + System.out.println("查看 " + i); + Skt = new Socket(host, i); + System.out.println("端口 " + i + " 已被使用"); + } catch (UnknownHostException e) { + System.out.println("Exception occured" + e); + break; + } catch (IOException e) { + } + } + } + + public static void InetAddress_localhost() { + InetAddress inetAddress = null; + try { + // 使用 InetAddress 类的 getLocalAddress() 方法获取本机ip地址及主机名 + inetAddress = InetAddress.getLocalHost(); + } catch (UnknownHostException u) { + u.printStackTrace(); + } + System.out.println("LocalHost Name: " + inetAddress.getHostName()); + System.out.println("LocalHost Address: " + inetAddress.getHostAddress()); + } + + public static void getContentLength(String URL) { + try { + URL url = new URL(URL); + URLConnection urlConnection = url.openConnection(); + System.out.println("Content Length: " + urlConnection.getContentLength() + " Bytes"); + } catch (MalformedURLException m) { + m.printStackTrace(); + } catch (IOException i) { + i.printStackTrace(); + } + } + + public static void getInetAddress(String url) { + try { + Socket socket = new Socket(url, 80); + InetAddress inetAddress = socket.getInetAddress(); + System.out.println("连接到: " + inetAddress); + socket.close(); + } catch (IOException i) { + System.out.println("无法连接到: " + url); + i.printStackTrace(); + } + } + + public static void url_openStream(String URL, File output) { + try { + URL url = new URL(URL); + // InputStreamReader:是字节流通往字符流的桥梁,使用指定的charset读取字节并解码成字符 + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(output)); + String line; + while ((line = bufferedReader.readLine()) != null) { + System.out.println(line); + bufferedWriter.write(line); + bufferedWriter.newLine(); + } + bufferedWriter.close(); + bufferedReader.close(); + } catch (MalformedURLException m) { + m.printStackTrace(); + } catch (IOException i) { + i.printStackTrace(); + } + } + + public static void URLConnection_getDate(String URL) { + try { + URL url = new URL(URL); + URLConnection urlConnection = url.openConnection(); + long time = urlConnection.getDate(); + if (time == 0) { + System.out.println("无法获取信息"); + } else { + System.out.println("URLConnection.getDate: " + new Date(time)); + } + } catch (MalformedURLException m) { + m.printStackTrace(); + } catch (IOException i) { + i.printStackTrace(); + } + } + + public static void URLConnection_getHeaderFields(String URL) { + try { + URL url = new URL(URL); + URLConnection urlConnection = url.openConnection(); + Map> fields = urlConnection.getHeaderFields(); + for (String key : fields.keySet()) { + System.out.printf("%s: %s%n", key, fields.get(key)); + } + } catch (IOException i) { + i.printStackTrace(); + } + } + + public static void url_info(String URL) { + try { + URL url = new URL(URL); + System.out.println("URL: " + url.toString()); + System.out.println("Protocol: " + url.getProtocol()); + System.out.println("File: " + url.getFile()); + System.out.println("Host: " + url.getHost()); + System.out.println("Path: " + url.getPath()); + System.out.println("Port: " + url.getPort()); + System.out.println("Default port: " + url.getDefaultPort()); + } catch (MalformedURLException m) { + m.printStackTrace(); + } + } + +} diff --git a/src/tutorial/examples/Server.java b/src/tutorial/examples/Server.java new file mode 100644 index 0000000..cb09ddd --- /dev/null +++ b/src/tutorial/examples/Server.java @@ -0,0 +1,37 @@ +package examples; + +import java.io.*; +import java.net.ServerSocket; +import java.net.Socket; + +/** + * Created by Oliver on 11/07/2017. + */ +public class Server { + /** + * 建立服务器端 + * 服务器建立通信ServerSocket + * 服务器建立Socket接收客户端连接 + * 建立IO输入流读取客户端发送的数据 + * 建立IO输出流向客户端发送数据消息 + */ + public static void main(String[] args) { + try { + ServerSocket serverSocket = new ServerSocket(8888); + System.out.println("启动服务器..."); + Socket socket = serverSocket.accept(); + System.out.printf("客户端: %s 连接到服务器%n", socket.getInetAddress()); + + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); + String msg = bufferedReader.readLine(); + System.out.println("客户端: " + msg); + + BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); + bufferedWriter.write(msg + "\n"); + bufferedWriter.flush(); + } catch (IOException i) { + i.printStackTrace(); + } + } + +} diff --git a/src/tutorial/examples/output.html b/src/tutorial/examples/output.html new file mode 100644 index 0000000..66abd93 --- /dev/null +++ b/src/tutorial/examples/output.html @@ -0,0 +1,2 @@ + + 百度一下,你就知道

关于百度 About Baidu

©2017 Baidu 使用百度前必读  意见反馈 京ICP证030173号 

diff --git a/src/tutorial/file/Files.java b/src/tutorial/file/Files.java index d9ad243..368d5b7 100644 --- a/src/tutorial/file/Files.java +++ b/src/tutorial/file/Files.java @@ -26,6 +26,7 @@ public static void Files_FileInputStream() throws IOException { FileInputStream fis = new FileInputStream(filePath); // 构建FileInputStream对象 // 构建InputStreamReader对象,编码与写入相同 + // InputStreamReader:是字节流通往字符流的桥梁,使用指定的charset读取字节并解码成字符 InputStreamReader reader = new InputStreamReader(fis, "UTF-8"); StringBuffer buffer = new StringBuffer(); From a28de1e8b2773da680e9046b169666d78ad16898 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Wed, 12 Jul 2017 17:28:44 +0800 Subject: [PATCH 35/41] thread --- src/tutorial/examples/ThreadExample.java | 290 +++++++++++++++++++++++ 1 file changed, 290 insertions(+) create mode 100644 src/tutorial/examples/ThreadExample.java diff --git a/src/tutorial/examples/ThreadExample.java b/src/tutorial/examples/ThreadExample.java new file mode 100644 index 0000000..919a97a --- /dev/null +++ b/src/tutorial/examples/ThreadExample.java @@ -0,0 +1,290 @@ +package examples; + +import java.io.IOException; +import java.util.Date; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +/** + * Created by Oliver on 11/07/2017. + */ +public class ThreadExample extends Thread { + public static String obj1 = "obj1"; + public static String obj2 = "obj2"; + private String threadName; + + + public static final Semaphore s1 = new Semaphore(1); + public static final Semaphore s2 = new Semaphore(1); + + public ThreadExample() { + + } + + public ThreadExample(String name) { + this.setName(name); + } + + + public static void main(String[] args) { + /* 通过继承 Thread 类并使用 isAlive() 方法来检测一个线程是否存活 */ + is_Alive(); + System.out.println(); + + /* 使用 currentThread.getState() 方法来监测线程的状态 */ + get_State(); + System.out.println(); + + /* 通过setPriority() 方法来设置线程的优先级 */ + set_Priority(); + System.out.println(); + + /* 线程挂起 */ + thread_join(); + + /* 终止线程 */ + thread_interrupt(); + + /* 通过线程解决生产者/消费者问题 */ + consumer_producer(); + + /* 死锁及解决方法 */ + lock_run(); + System.out.println(); + } + + public void run() { + try { + for (int i = 0; i < 10; i++) { + printMsg(); + } + Thread.sleep(3000); //使用interrupt方法,sleep方法将抛出一个InterruptedException例外 + } catch (InterruptedException i) { + System.out.println(i.getMessage()); + } + + } + + public static void printMsg() { + Thread thread = Thread.currentThread(); + String name = thread.getName(); //使用 getName() 方法来获取当前线程名称 + System.out.println("Thread: " + name + ", ID: " + thread.getId()); + } + + public static void showThreadStatus(Thread thread) { + System.out.printf("Thread %s status: %s%n", thread.getName(), thread.getState()); + } + + public static void is_Alive() { + ThreadExample threadExample = new ThreadExample("Thread-isAlive"); + System.out.println(threadExample.getName() + " before start: " + threadExample.isAlive()); + threadExample.start(); + System.out.println(threadExample.getName() + " after start: " + threadExample.isAlive()); + for (int i = 0; i < 5; i++) { + printMsg(); + } + } + + public static void get_State() { + try { + ThreadExample threadExample = new ThreadExample("Thread-getState"); + showThreadStatus(threadExample); + + threadExample.start(); + Thread.sleep(1000); + showThreadStatus(threadExample); + } catch (InterruptedException i) { + i.printStackTrace(); + } + } + + public static void set_Priority() { + try { + ThreadExample threadExampleMax = new ThreadExample(); + ThreadExample threadExampleMin = new ThreadExample(); + threadExampleMax.setName("Thread-setPriority-max"); + threadExampleMin.setName("Thread-setPriority-min"); + threadExampleMax.setPriority(Thread.MAX_PRIORITY); + threadExampleMin.setPriority(Thread.MIN_PRIORITY); + threadExampleMax.start(); + threadExampleMin.start(); + showThreadStatus(threadExampleMax); + showThreadStatus(threadExampleMin); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void lock_run() { + LockA lockA = new LockA(); + new Thread(lockA).start(); + LockB lockB = new LockB(); + new Thread(lockB).start(); + } + + public static void thread_join() { + try { + for (int i = 0; i < 5; i++) { + ThreadExample threadExample = new ThreadExample(); + threadExample.setName("Thread-join"); + threadExample.start(); + threadExample.join(); + } + System.out.println("线程已被挂起"); + } catch (InterruptedException i) { + i.printStackTrace(); + } + } + + public static void thread_interrupt() { + try { + ThreadExample threadExample = new ThreadExample("Thread-interrupt"); + threadExample.start(); + System.out.println("在5秒之内按任意键中断线程!"); + System.in.read(); + threadExample.interrupt(); + threadExample.join(); + System.out.println("线程已经退出!"); + } catch (IOException i) { + i.printStackTrace(); + } catch (InterruptedException i) { + i.printStackTrace(); + } + } + + public static void consumer_producer() { + CubbyHole cubbyHole = new CubbyHole(); + Producer producer = new Producer(cubbyHole, 1); + Consumer consumer = new Consumer(cubbyHole, 1); + producer.start(); + consumer.start(); + } +} + +class LockA implements Runnable { + public void run() { + try { + System.out.println(new Date().toString() + " LockA 开始执行"); + while (true) { + if (ThreadExample.s1.tryAcquire(1, TimeUnit.SECONDS)) { + System.out.println(new Date().toString() + " LockA 锁住obj1"); + Thread.sleep(3000); // 此处等待是给B能锁住机会 + if (ThreadExample.s2.tryAcquire(1, TimeUnit.SECONDS)) { + System.out.println(new Date().toString() + " LockA 锁住obj2"); + Thread.sleep(60 * 1000); // 为测试,占用了就不放 + } else { + System.out.println(new Date().toString() + " LockA 锁住obj2失败"); + } + } else { + System.out.println(new Date().toString() + " LockA 锁住obj1失败"); + } + ThreadExample.s1.release(); //释放 + ThreadExample.s2.release(); + Thread.sleep(1000); //马上进行尝试,现实情况下do something是不确定的 + } + } catch (InterruptedException i) { + i.printStackTrace(); + } + } +} + +class LockB implements Runnable { + public void run() { + try { + System.out.println(new Date().toString() + " LockB 开始执行"); + while (true) { + if (ThreadExample.s2.tryAcquire(1, TimeUnit.SECONDS)) { + System.out.println(new Date().toString() + " LockB 锁住obj2"); + Thread.sleep(3000); // 此处等待是给A能锁住机会 + if (ThreadExample.s1.tryAcquire(1, TimeUnit.SECONDS)) { + System.out.println(new Date().toString() + " LockB 锁住obj1"); + Thread.sleep(60 * 1000); // 为测试,占用了就不放 + } else { + System.out.println(new Date().toString() + " LockB 锁住obj1失败"); + } + } else { + System.out.println(new Date().toString() + " LockB 锁住obj2失败"); + } + ThreadExample.s1.release(); + ThreadExample.s2.release(); + Thread.sleep(1000); //这里只是为了演示,所以tryAcquire只用1秒,而且B要给A让出能执行的时间,否则两个永远是死锁 + } + } catch (InterruptedException i) { + i.printStackTrace(); + } + } +} + +class CubbyHole { + private int contents; + private boolean available = false; + + public synchronized int get() { + while (available == false) { + try { + wait(); + } catch (InterruptedException i) { + i.printStackTrace(); + } + } + available = false; + notifyAll(); + return contents; + } + + public synchronized void put(int value) { + while (available == true) { + try { + wait(); + } catch (InterruptedException i) { + i.printStackTrace(); + } + } + contents = value; + available = true; + notifyAll(); + } + +} + +class Consumer extends Thread { + private CubbyHole cubbyHole; + private int number; + + Consumer(CubbyHole cubbyHole, int number) { + this.cubbyHole = cubbyHole; + this.number = number; + } + + public void run() { + int value; + for (int i = 0; i < 10; i++) { + value = cubbyHole.get(); + System.out.println("消费者 #" + this.number + " got: " + value); + } + } +} + +class Producer extends Thread { + private CubbyHole cubbyHole; + private int number; + + Producer(CubbyHole cubbyHole, int number) { + this.cubbyHole = cubbyHole; + this.number = number; + } + + public void run() { + try { + for (int i = 0; i < 10; i++) { + cubbyHole.put(i); + System.out.println("生产者 #" + this.number + " put: " + i); + Thread.sleep(1000); + } + } catch (InterruptedException i) { + i.printStackTrace(); + } + + } +} + From 4d20e73c62c23f8754ed48f3c7d46ab3dac4ba2c Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Thu, 13 Jul 2017 11:27:21 +0800 Subject: [PATCH 36/41] method reference, functional interface, lambda --- src/tutorial/java8/FunctionalInterface.java | 60 +++++++++++++++ src/tutorial/java8/Lambda.java | 83 +++++++++++++++++++++ src/tutorial/java8/MethodReference.java | 53 +++++++++++++ 3 files changed, 196 insertions(+) create mode 100644 src/tutorial/java8/FunctionalInterface.java create mode 100644 src/tutorial/java8/Lambda.java create mode 100644 src/tutorial/java8/MethodReference.java diff --git a/src/tutorial/java8/FunctionalInterface.java b/src/tutorial/java8/FunctionalInterface.java new file mode 100644 index 0000000..0a9bb8a --- /dev/null +++ b/src/tutorial/java8/FunctionalInterface.java @@ -0,0 +1,60 @@ +package java8; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Predicate; + +/** + * Created by Oliver on 13/07/2017. + */ +public class FunctionalInterface { + /** + * 函数式接口(Functional Interface)就是一个具有一个方法的普通接口。 + * 函数式接口可以被隐式转换为lambda表达式。 + * 函数式接口可以现有的函数友好地支持 lambda。 + */ + public static void main(String[] args) { + List integerList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); + integerList.forEach(System.out::println); + + System.out.println("输出所有数据:"); + /** + * Predicate predicate = n -> true + * n 是一个参数传递到 Predicate 接口的 test 方法 + * n 如果存在则 test 方法返回 true + */ + eval(integerList, n -> true); + + System.out.println("输出所有偶数:"); + /** + * Predicate predicate1 = n -> n%2 == 0 + * n 是一个参数传递到 Predicate 接口的 test 方法 + * 如果 n%2 为 0 test 方法返回 true + */ + eval(integerList, n -> n % 2 == 0); + + System.out.println("输出大于3的数字:"); + /** + * Predicate predicate1 = n -> n%2 == 0 + * n 是一个参数传递到 Predicate 接口的 test 方法 + * 如果 n大于3 test 方法返回 true + */ + eval(integerList, n -> n > 3); + + } + + public static void eval(List list, Predicate predicate) { + /** + * Predicate 接口是一个函数式接口,它接受一个输入参数 T,返回一个布尔值结果。 + * 该接口包含多种默认方法来将Predicate组合成其他复杂的逻辑(比如:与,或,非)。 + * 该接口用于测试对象是 true 或 false。 + */ + for (Integer i : list) { + if (predicate.test(i)) { + System.out.print(i + " "); + } + } + System.out.println(); + } + +} diff --git a/src/tutorial/java8/Lambda.java b/src/tutorial/java8/Lambda.java new file mode 100644 index 0000000..54b766d --- /dev/null +++ b/src/tutorial/java8/Lambda.java @@ -0,0 +1,83 @@ +package java8; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +/** + * Created by Oliver on 12/07/2017. + */ +public class Lambda { + public static void main(String[] args) { + List names = new ArrayList<>(); + names.add("Google"); + names.add("Bing"); + names.add("JD"); + + sort_java7(names); + sort_java8(names); + + tryLambda(); + } + + public static void sort_java7(List list) { + Collections.sort(list, new Comparator() { + @Override + public int compare(String o1, String o2) { + return o1.compareTo(o2); + } + }); + System.out.println(list); + } + + // Lambda允许把函数作为一个方法的参数 + public static void sort_java8(List list) { + Collections.sort(list, (s1, s2) -> s1.compareTo(s2)); +// Collections.sort(list, String::compareTo); + System.out.println(list); + } + + /** + * Lambda 表达式主要用来定义行内执行的方法类型接口. 例如,一个简单方法接口。 + * 在下面例子中,我们使用各种类型的Lambda表达式来定义MathOperation接口的方法。 + * 然后我们定义了sayMessage的执行。 + */ + public static void tryLambda() { + // 类型声明 + MathOperation addition = (int a, int b) -> a + b; + // 不用类型声明 + MathOperation subtract = (a, b) -> a - b; + // 大括号中的返回语句 + MathOperation multiply = (a, b) -> { + return a * b; + }; + // 没有大括号及返回语句 + MathOperation divide = (a, b) -> a / b; + + System.out.println("10 + 20 = " + operate(10, 20, addition)); + System.out.println("20 - 10 = " + operate(20, 10, subtract)); + System.out.println("10 * 20 = " + operate(10, 20, multiply)); + System.out.println("20 / 10 = " + operate(20, 10, divide)); + + GreetingService greetingService1 = message -> System.out.println("Hi, " + message); // 不用括号 + GreetingService greetingService2 = (message) -> System.out.println("Greetings, " + message); // 用括号 + greetingService1.sayMessage("Google"); + greetingService2.sayMessage("Apple"); + + } + + private static int operate(int a, int b, MathOperation mathOperation) { + return mathOperation.operation(a, b); + } + + interface MathOperation { + int operation(int a, int b); + } + + interface GreetingService { + void sayMessage(String message); + } + + +} diff --git a/src/tutorial/java8/MethodReference.java b/src/tutorial/java8/MethodReference.java new file mode 100644 index 0000000..71f44b2 --- /dev/null +++ b/src/tutorial/java8/MethodReference.java @@ -0,0 +1,53 @@ +package java8; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Supplier; + +/** + * Created by Oliver on 13/07/2017. + */ +public class MethodReference { + /** + * 方法引用通过方法的名字来指向一个方法。 + * 方法引用可以使语言的构造更紧凑简洁,减少冗余代码。 + * 方法引用使用一对冒号(::)。 + * 下面,我们以定义了4个方法的Car这个类作为例子,区分Java中支持的4种不同的方法引用 + */ + public static void main(String[] args) { + // 构造器引用:它的语法是Class::new,或者更一般的Class< T >::new实例如下: + Car car = Car.create(Car::new); + List cars = Arrays.asList(car); + + // 静态方法引用:它的语法是Class::static_method,实例如下: + cars.forEach(Car::collide); + + // 特定类的任意对象的方法引用:它的语法是Class::method实例如下: + cars.forEach(Car::repair); + + // 特定对象的方法引用:它的语法是instance::method实例如下 + Car police = Car.create(Car::new); + cars.forEach(police::follow); + + // 将 System.out::println 方法作为静态方法来引用。 + cars.forEach(System.out::println); + } +} + +class Car { + static Car create(Supplier supplier) { + return supplier.get(); + } + + static void collide(Car car) { + System.out.println("Collided: " + car.toString()); + } + + void follow(Car another) { + System.out.println(this + " following: " + another.toString()); + } + + void repair() { + System.out.println("Repairing: " + this.toString()); + } +} \ No newline at end of file From 174bffe82b2200e864b64d9f97ceea3a502e564a Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Thu, 13 Jul 2017 18:46:00 +0800 Subject: [PATCH 37/41] default method, stream --- src/tutorial/java8/DefaultMethod.java | 40 +++++++++++ src/tutorial/java8/Lambda.java | 2 - src/tutorial/java8/Stream.java | 97 +++++++++++++++++++++++++++ 3 files changed, 137 insertions(+), 2 deletions(-) create mode 100644 src/tutorial/java8/DefaultMethod.java create mode 100644 src/tutorial/java8/Stream.java diff --git a/src/tutorial/java8/DefaultMethod.java b/src/tutorial/java8/DefaultMethod.java new file mode 100644 index 0000000..9993f99 --- /dev/null +++ b/src/tutorial/java8/DefaultMethod.java @@ -0,0 +1,40 @@ +package java8; + +/** + * Created by Oliver on 13/07/2017. + */ +public class DefaultMethod implements Bus, Jet { + /** + * 默认方法就是接口可以有实现方法,而且不需要实现类去实现其方法。 + * 我们只需在方法名前面加个default关键字即可实现默认方法 + */ + public static void main(String[] args) { + DefaultMethod defaultMethod = new DefaultMethod(); + defaultMethod.printSelf(); + Bus.blowHorn(); + } + + //使用 super 来调用指定接口的默认方法: + public void printSelf() { + Bus.super.printSelf(); + } +} + +interface Bus { + default void printSelf() { + System.out.println("I'm bus"); + } + + /** + * Java 8 的另一个特性是接口可以声明(并且可以提供实现)静态方法 + */ + static void blowHorn() { + System.out.println("按喇叭!!!"); + } +} + +interface Jet { + default void printSelf() { + System.out.println("I'm jet"); + } +} \ No newline at end of file diff --git a/src/tutorial/java8/Lambda.java b/src/tutorial/java8/Lambda.java index 54b766d..7dc3938 100644 --- a/src/tutorial/java8/Lambda.java +++ b/src/tutorial/java8/Lambda.java @@ -64,7 +64,6 @@ public static void tryLambda() { GreetingService greetingService2 = (message) -> System.out.println("Greetings, " + message); // 用括号 greetingService1.sayMessage("Google"); greetingService2.sayMessage("Apple"); - } private static int operate(int a, int b, MathOperation mathOperation) { @@ -79,5 +78,4 @@ interface GreetingService { void sayMessage(String message); } - } diff --git a/src/tutorial/java8/Stream.java b/src/tutorial/java8/Stream.java new file mode 100644 index 0000000..68e4b3b --- /dev/null +++ b/src/tutorial/java8/Stream.java @@ -0,0 +1,97 @@ +package java8; + +import java.util.Arrays; +import java.util.IntSummaryStatistics; +import java.util.List; +import java.util.Random; +import java.util.stream.Collectors; + +/** + * Created by Oliver on 13/07/2017. + */ +public class Stream { + public static void main(String[] args) { + + /** + * 在 Java 8 中, 集合接口有两个方法来生成流: + * stream() − 为集合创建串行流。 + * parallelStream() − 为集合创建并行流。 + */ + stream(); + + /* Stream 提供了新的方法 'forEach' 来迭代流中的每个数据。以下代码片段使用 forEach 输出了10个随机数 */ + /* limit 方法用于获取指定数量的流。 以下代码片段使用 limit 方法打印出 5 条数据 */ + foreach_limit(5); + + /* map 方法用于映射每个元素到对应的结果,以下代码片段使用 map 输出了元素对应的平方数 */ + map(); + + /*filter 方法用于通过设置的条件过滤出元素。以下代码片段使用 filter 方法过滤出空字符串 */ + filter(); + + /* sorted 方法用于对流进行排序。以下代码片段使用 sorted 方法对输出的 5 个随机数进行排序 */ + sort(5); + + /* parallelStream 是流并行处理程序的代替方法。以下实例我们使用 parallelStream 来输出空字符串的数量 */ + parallelStream(); + + /* Collectors 类实现了很多归约操作,例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串 */ + collectors(); + + /* 另外,一些产生统计结果的收集器也非常有用。它们主要用于int、double、long等基本类型上,它们可以用来产生类似如下的统计结果 */ + summaryStatistics(); + } + + public static void stream() { + List list = Arrays.asList("abc", "", "bc", "efg", "abd", "", "jkl"); + List filtered = list.stream().filter(string -> !list.isEmpty()).collect(Collectors.toList()); + filtered.forEach(System.out::println); + } + + public static void foreach_limit(int limit) { + Random random = new Random(); + random.ints().limit(limit).forEach(System.out::println); + } + + public static void map() { + List list = Arrays.asList(3, 2, 2, 3, 7, 3, 5); + List squares = list.stream().map(x -> x * x).distinct().collect(Collectors.toList()); + squares.forEach(System.out::println); + } + + public static void filter() { + List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 7); + List filtered = list.stream().filter(i -> i == 7).collect(Collectors.toList()); + filtered.forEach(System.out::println); + } + + public static void sort(int limit) { + Random random = new Random(); + random.ints().limit(limit).sorted().forEach(System.out::println); + } + + public static void parallelStream() { + List list = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl"); + long count = list.parallelStream().filter(string -> string.isEmpty()).count(); + System.out.println("Empty string: " + count); + } + + public static void collectors() { + List list = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl"); + List filtered = list.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList()); + System.out.println("Collectors返回列表: " + filtered); + + String merged = list.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", ")); + System.out.println("Collectors返回字符串: " + merged); + } + + public static void summaryStatistics() { + List numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); + IntSummaryStatistics intSummaryStatistics = numbers.stream().mapToInt(x -> x).summaryStatistics(); + System.out.println("列表中最大的数: " + intSummaryStatistics.getMax()); + System.out.println("列表中最小的数: " + intSummaryStatistics.getMin()); + System.out.println("所有数之和: " + intSummaryStatistics.getSum()); + System.out.println("平均数: " + intSummaryStatistics.getAverage()); + } + +} From c074eedb055766d08c6d66a4cfdf23b5943cdf2d Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Fri, 14 Jul 2017 00:09:26 +0800 Subject: [PATCH 38/41] Optional --- src/tutorial/java8/Optionals.java | 39 +++++++++++++++++++++++++++++++ src/tutorial/java8/Stream.java | 18 ++++++++++---- 2 files changed, 53 insertions(+), 4 deletions(-) create mode 100644 src/tutorial/java8/Optionals.java diff --git a/src/tutorial/java8/Optionals.java b/src/tutorial/java8/Optionals.java new file mode 100644 index 0000000..189f064 --- /dev/null +++ b/src/tutorial/java8/Optionals.java @@ -0,0 +1,39 @@ +package java8; + +import java.util.Optional; + +/** + * Created by Oliver on 13/07/2017. + */ +public class Optionals { + /** + * Optional 类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。 + * Optional 是个容器:它可以保存类型T的值,或者仅仅保存null。Optional提供很多有用的方法,这样我们就不用显式进行空值检测。 + * Optional 类的引入很好的解决空指针异常。 + */ + public static void main(String[] args) { + Integer value1 = null; + Integer value2 = new Integer(10); + + // Optional.ofNullable - 允许传递为 null 参数 + Optional a = Optional.ofNullable(value1); + Optional b = Optional.of(value2); + + System.out.println("a + b = " + sum(a, b)); + + } + + public static Integer sum(Optional a, Optional b) { + // Optional.isPresent - 判断值是否存在 + System.out.println("第一个参数值存在: " + a.isPresent()); + System.out.println("第二个参数值存在: " + b.isPresent()); + + // Optional.orElse - 如果值存在,返回它,否则返回默认值 + Integer value1 = a.orElse(new Integer(1)); + Integer value2 = b.get(); + + return value1 + value2; + } + + +} diff --git a/src/tutorial/java8/Stream.java b/src/tutorial/java8/Stream.java index 68e4b3b..c45eee5 100644 --- a/src/tutorial/java8/Stream.java +++ b/src/tutorial/java8/Stream.java @@ -11,12 +11,18 @@ */ public class Stream { public static void main(String[] args) { - /** - * 在 Java 8 中, 集合接口有两个方法来生成流: - * stream() − 为集合创建串行流。 - * parallelStream() − 为集合创建并行流。 + * Java 8 API添加了一个新的抽象称为流Stream,可以让你以一种声明的方式处理数据。 + * Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。 + * Stream API可以极大提供Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。 + * 这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等 + * 元素流在管道中经过中间操作(intermediate operation)的处理,最后由最终操作(terminal operation)得到前面处理的结果。 + * + * | stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect| */ + + + // stream() − 为集合创建串行流。 stream(); /* Stream 提供了新的方法 'forEach' 来迭代流中的每个数据。以下代码片段使用 forEach 输出了10个随机数 */ @@ -68,6 +74,10 @@ public static void filter() { public static void sort(int limit) { Random random = new Random(); random.ints().limit(limit).sorted().forEach(System.out::println); + + List list = Arrays.asList("abc", "", "bc", "efg", "abd", "", "jkl"); + List sorted = list.stream().sorted(String::compareTo).collect(Collectors.toList()); + System.out.println("sorted string list: " + sorted); } public static void parallelStream() { From 89da3b97907842ddc9f703fc15cc6e2e676a6fa7 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Fri, 14 Jul 2017 13:31:00 +0800 Subject: [PATCH 39/41] java.time --- src/tutorial/java8/Time.java | 64 ++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/tutorial/java8/Time.java diff --git a/src/tutorial/java8/Time.java b/src/tutorial/java8/Time.java new file mode 100644 index 0000000..10f9392 --- /dev/null +++ b/src/tutorial/java8/Time.java @@ -0,0 +1,64 @@ +package java8; + +import java.time.*; + +/** + * Created by Oliver on 14/07/2017. + */ +public class Time { + /** + * Java 8 在 java.time 包下提供了很多新的 API。以下为两个比较重要的 API: + * Local(本地) − 简化了日期时间的处理,没有时区的问题。 + * Zoned(时区) − 通过制定的时区处理日期时间。 + *

+ * 新的java.time包涵盖了所有处理日期,时间,日期/时间,时区,时刻(instants),过程(during)与时钟(clock)的操作。 + */ + public static void main(String[] args) { + + /* 本地化日期时间 API */ + localDateTime(); + + /* 使用时区的日期时间API */ + zonedDateTime(); + } + + public static void localDateTime() { + // LocalDateTime + LocalDateTime localDateTime = LocalDateTime.now(); + System.out.println("LocalDataTime.now: " + localDateTime); + System.out.println("Month: " + localDateTime.getMonth()); + System.out.println("Day: " + localDateTime.getDayOfMonth()); + System.out.println("Minute: " + localDateTime.getMinute()); + System.out.println("Seconds: " + localDateTime.getSecond()); + LocalDateTime localDateTime1 = localDateTime.withDayOfMonth(15).withYear(2018); + System.out.println("LocalDateTime1: " + localDateTime1); + + // LocalDate + LocalDate localDate = localDateTime.toLocalDate(); + System.out.println("LocalDate: " + localDate); + LocalDate localDate1 = LocalDate.of(2019, 8, 15); + System.out.println("LocalDate1: " + localDate1); + + // LocalTime + LocalTime localTime = LocalTime.now(); + System.out.println("LocalTime.now: " + localTime); + LocalTime localTime1 = LocalTime.of(12, 15); + System.out.println("LocalTime1: " + localTime1); + LocalTime localTime2 = LocalTime.parse("13:15:30"); + System.out.println("Parse local time hour: " + localTime2.getHour()); + } + + public static void zonedDateTime() { + ZonedDateTime zonedDateTime = ZonedDateTime.now(); + System.out.println("ZonedDateTime: " + zonedDateTime); + + ZonedDateTime zonedDateTime1 = ZonedDateTime.parse("2018-08-15T13:24:46.506+08:00[Asia/Shanghai]"); + System.out.println("Parse zoned dat time zone: " + zonedDateTime1.getZone()); + + ZoneId zoneId = ZoneId.of("Europe/Paris"); + System.out.println("ZonedId: " + zoneId); + + ZoneId currentZone = ZoneId.systemDefault(); + System.out.println("ZonedId.systemDefault: " + currentZone); + } +} From 571a0a6014a87fb3a78804930d30346e1202dda4 Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Fri, 14 Jul 2017 14:50:20 +0800 Subject: [PATCH 40/41] Base64 --- src/tutorial/java8/BASE64.java | 45 ++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/tutorial/java8/BASE64.java diff --git a/src/tutorial/java8/BASE64.java b/src/tutorial/java8/BASE64.java new file mode 100644 index 0000000..67b3787 --- /dev/null +++ b/src/tutorial/java8/BASE64.java @@ -0,0 +1,45 @@ +package java8; + +import java.io.UnsupportedEncodingException; +import java.util.Base64; +import java.util.UUID; + +/** + * Created by Oliver on 14/07/2017. + */ +public class BASE64 { + public static void main(String[] args) { + try { + /**使用基本编码 + * 基本:输出被映射到一组字符A-Za-z0-9+/,编码不添加任何行标,输出的解码仅支持A-Za-z0-9+/。 + */ + String base64encodedString = Base64.getEncoder().encodeToString("oracle?java8".getBytes("UTF-8")); + System.out.println("Base64编码字符串(基本): " + base64encodedString); + + // 解码 + byte[] base64decodedBytes = Base64.getDecoder().decode(base64encodedString); + System.out.println("Base64解码: " + new String(base64decodedBytes, "UTF-8")); + + /**使用URL编码 + * URL:输出映射到一组字符A-Za-z0-9+_,输出是URL和文件。 + */ + base64encodedString = Base64.getUrlEncoder().encodeToString("TutorialsPoint?java8".getBytes("UTF-8")); + System.out.println("Base64编码字符串(url): " + base64encodedString); + + + StringBuilder stringBuilder = new StringBuilder(); + String uuid = UUID.randomUUID().toString(); + System.out.println("Random uuid: " + uuid); + stringBuilder.append(uuid); + + /**使用MIME编码 + * MIME:输出隐射到MIME友好格式。输出每行不超过76字符,并且使用'\r'并跟随'\n'作为分割。编码输出最后没有行分割。 + */ + byte[] mimeBytes = stringBuilder.toString().getBytes("UTF-8"); + base64encodedString = Base64.getMimeEncoder().encodeToString(mimeBytes); + System.out.println("Base64编码字符串(MIME): " + base64encodedString); + } catch (UnsupportedEncodingException u) { + u.printStackTrace(); + } + } +} From 4f67fb9c2bca269e6df35f791b8788514e4e64fa Mon Sep 17 00:00:00 2001 From: Oliver Luan Date: Fri, 14 Jul 2017 17:36:26 +0800 Subject: [PATCH 41/41] mysql --- .../interfacetest/utils/ConnectToDB.java | 127 +++++++++--------- src/tutorial/db/MySQL.java | 81 +++++++++++ src/tutorial/db/mysql.properties | 4 + 3 files changed, 150 insertions(+), 62 deletions(-) create mode 100644 src/tutorial/db/MySQL.java create mode 100644 src/tutorial/db/mysql.properties diff --git a/src/main/java/com/vipabc/interfacetest/utils/ConnectToDB.java b/src/main/java/com/vipabc/interfacetest/utils/ConnectToDB.java index e5bddfb..d7b195f 100644 --- a/src/main/java/com/vipabc/interfacetest/utils/ConnectToDB.java +++ b/src/main/java/com/vipabc/interfacetest/utils/ConnectToDB.java @@ -11,102 +11,105 @@ public class ConnectToDB { - private Connection conn; + private Connection conn; - public ConnectToDB() { - String driver = "com.mysql.cj.jdbc.Driver"; + public ConnectToDB() { + String driver = "com.mysql.cj.jdbc.Driver"; - String url = "jdbc:mysql://172.16.233.82:3306/vfs"; + String url = "jdbc:mysql://172.16.233.82:3306/vfs"; - String user = "vfsdev"; + String user = "vfsdev"; - String password = "vfs123"; + String password = "vfs123"; - try { - Class.forName(driver); - conn = DriverManager.getConnection(url, user, password); - if (!conn.isClosed()) - System.out.println("Succeeded connecting to the Database!"); - } catch (ClassNotFoundException e) { + try { + Class.forName(driver); + conn = DriverManager.getConnection(url, user, password); + if (!conn.isClosed()) + System.out.println("Succeeded connecting to the Database!"); + } catch (ClassNotFoundException e) { - System.out.println("Sorry,can't find the Driver!"); - e.printStackTrace(); + System.out.println("Sorry,can't find the Driver!"); + e.printStackTrace(); - } catch (SQLException e) { + } catch (SQLException e) { - e.printStackTrace(); + e.printStackTrace(); - } catch (Exception e) { + } catch (Exception e) { - e.printStackTrace(); + e.printStackTrace(); - } - } + } + } - public List> query(String table, String key) throws SQLException { - Statement statement = conn.createStatement(); + public List> query(String table, String key) throws SQLException { + Statement statement = conn.createStatement(); ResultSet rs = statement.executeQuery("select * from " + table); List> result = new ArrayList>(); ResultSetMetaData md = rs.getMetaData(); int cc = md.getColumnCount(); - while (rs.next()) { + while (rs.next()) { HashMap columnMap = new HashMap(); for (int i = 1; i <= cc; i++) { columnMap.put(md.getColumnName(i), rs.getString(i)); } result.add(columnMap); - } - rs.close(); - conn.close(); - return result; - } + } + rs.close(); + conn.close(); + return result; + } - public List> query(String sql) throws SQLException { - Statement statement = conn.createStatement(); - ResultSet rs = statement.executeQuery(sql); - List> result = new ArrayList>(); + public List> query(String sql) throws SQLException { + Statement statement = conn.createStatement(); + ResultSet rs = statement.executeQuery(sql); + List> result = new ArrayList>(); ResultSetMetaData md = rs.getMetaData(); int cc = md.getColumnCount(); - while (rs.next()) { + while (rs.next()) { HashMap columnMap = new HashMap(); for (int i = 1; i <= cc; i++) { columnMap.put(md.getColumnName(i), rs.getString(i)); } result.add(columnMap); - } - rs.close(); + } + rs.close(); // conn.close(); return result; - } - - public void insert(String sql) throws SQLException { - Statement statement = conn.createStatement(); - statement.executeUpdate(sql); - } - public void update(String sql) throws SQLException { - Statement statement = conn.createStatement(); - statement.executeUpdate(sql); - } - public void delete(String sql) throws SQLException { - Statement statement = conn.createStatement(); - statement.executeUpdate(sql); - } - public void closeDBcon(){ - try { - conn.close(); - } catch (SQLException ex) { - Logger.getLogger(Oracle.class.getName()).log(Level.SEVERE, null, ex); - } - } - - public static void main(String args[]) throws SQLException { - ConnectToDB cdb = new ConnectToDB(); - cdb.query("visit_identitify_code", "code_value"); - cdb.query("visit_identitify_code", "status"); + } + + public void insert(String sql) throws SQLException { + Statement statement = conn.createStatement(); + statement.executeUpdate(sql); + } + + public void update(String sql) throws SQLException { + Statement statement = conn.createStatement(); + statement.executeUpdate(sql); + } + + public void delete(String sql) throws SQLException { + Statement statement = conn.createStatement(); + statement.executeUpdate(sql); + } + + public void closeDBcon() { + try { + conn.close(); + } catch (SQLException ex) { + Logger.getLogger(Oracle.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public static void main(String args[]) throws SQLException { + ConnectToDB cdb = new ConnectToDB(); + cdb.query("visit_identitify_code", "code_value"); + cdb.query("visit_identitify_code", "status"); // cdb.insert("INSERT INTO visit_identitify_code" // + " (`id`, `creater`, `create_time`, `modifier`, `modify_time`, `version`, `code_value`, `follow_id`, `status`, `client_linkman_id`)" // + "VALUES (3, -1, '2014/5/29 17:00:00', NULL, NULL, 0, '4321', 1, 'visiting', 1);"); - } + } } diff --git a/src/tutorial/db/MySQL.java b/src/tutorial/db/MySQL.java new file mode 100644 index 0000000..86733ca --- /dev/null +++ b/src/tutorial/db/MySQL.java @@ -0,0 +1,81 @@ +package db; + +import java.io.IOException; +import java.io.InputStream; +import java.sql.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; + +/** + * Created by Oliver on 14/07/2017. + */ +public class MySQL { + /** + * 使用 JDBC 连接 MySQL 数据库。 + * Java 连接 MySQL 需要驱动包,最新版下载地址为:http://dev.mysql.com/downloads/connector/j/,解压后得到jar库文件,然后在对应的项目中导入该库文件。 + */ + private Properties properties = System.getProperties(); + private Connection connection; + + public static void main(String[] args) { + MySQL mySQL = new MySQL(); + System.out.println("SQL return: " + mySQL.query("SELECT * FROM products_jd ORDER BY ID DESC LIMIT 5")); + } + + public void getConnect() { + try { + InputStream inputStream = MySQL.class.getResourceAsStream("mysql.properties"); + properties.load(inputStream); + + String driver = properties.getProperty("mysql.driver"); + String url = properties.getProperty("mysql.url"); + String user = properties.getProperty("mysql.user"); + String password = properties.getProperty("mysql.password"); + + // 注册 JDBC 驱动 + Class.forName(driver); + + // 打开链接 + System.out.println("连接数据库..."); + connection = DriverManager.getConnection(url, user, password); + } catch (IOException i) { + i.printStackTrace(); + } catch (ClassNotFoundException c) { + c.printStackTrace(); + } catch (SQLException s) { + s.printStackTrace(); + } + } + + public List> query(String s) { + getConnect(); + HashMap result = new HashMap<>(); + List> results = new ArrayList<>(); + try { + // 执行查询 + System.out.println(" 实例化Statement对..."); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(s); + + // 分析返回结果 + ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); + int columnCount = resultSetMetaData.getColumnCount(); + while (resultSet.next()) { + for (int i = 1; i <= columnCount; i++) { + System.out.print(resultSetMetaData.getColumnLabel(i) + ":" + resultSet.getString(i) + ", "); + result.put(resultSetMetaData.getColumnLabel(i), resultSet.getString(i)); + } + System.out.println(); + results.add(result); + } + resultSet.close(); + statement.close(); + connection.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + return results; + } +} diff --git a/src/tutorial/db/mysql.properties b/src/tutorial/db/mysql.properties new file mode 100644 index 0000000..93e11ed --- /dev/null +++ b/src/tutorial/db/mysql.properties @@ -0,0 +1,4 @@ +mysql.driver=com.mysql.cj.jdbc.Driver +mysql.url=jdbc:mysql://localhost:3306/spider +mysql.user=root +mysql.password=password \ No newline at end of file