Math类 概述 Math类所在包为java.lang包,因此在使用的时候不需要进行导包。并且Math类被final修饰了,因此该类是不能被继承的。
Math类包含执行基本数字运算的方法,我们可以使用Math类完成基本的数学运算。
Math类中的方法都是静态的,因此在使用的时候我们可以直接通过类名去调用。
常见方法 Math的常见方法如下所示:
1 2 3 4 5 6 7 8 public static int abs (int a) public static double ceil (double a) public static double floor (double a) public static int round (float a) public static int max (int a,int b) public static int min (int a,int b) public static double pow (double a,double b) public static double random ()
算法题(质数) 需求:判断一个数是否为一个质数
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public class MathDemo2 { public static void main (String[] args) { System.out.println(isPrime(997 )); } public static boolean isPrime (int number) { int count = 0 ; for (int i = 2 ; i <= Math.sqrt(number); i++) { count++; if (number % i == 0 ) { return false ; } } System.out.println(count); return true ; } }
算法题(自幂数) 自幂数,一个n位自然数等于自身各个数位上数字的n次幂之和
举例1:三位数 1^3 + 5^3 + 3^3 = 153
举例2:四位数 1^4 + 6^4 + 3^4 + 4^3 = 1634
如果自幂数是:
一位自幂数,也叫做:独身数
三位自幂数:水仙花数 四位自幂数:四叶玫瑰数
五位自幂数:五角星数 六位自幂数:六合数
七位自幂数:北斗七星数 八位自幂数:八仙数
九位自幂数:九九重阳数 十位自幂数:十全十美数
要求:统计一共有多少个水仙花数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 int count = 0 ;for (int i = 100 ; i <= 999 ; i++) { int ge = i % 10 ; int shi = i / 10 % 10 ; int bai = i / 100 % 10 ; double sum = Math.pow(ge, 3 ) + Math.pow(shi, 3 ) + Math.pow(bai, 3 ); if (sum == i) { count++; System.out.println(count); } }
System类 概述 System类所在包为java.lang包,因此在使用的时候不需要进行导包。并且System类被final修饰了,因此该类是不能被继承的。
System包含了系统操作的一些常用的方法。比如获取当前时间所对应的毫秒值,再比如终止当前JVM等等。
在API文档中没有体现可用的构造方法,因此我们就不能直接通过new关键字去创建System类的对象。同时我们发现System类中的方法都是静态的,因此在使用的时候我们可以直接通过类名去调用(Nested
Class Summary内部类或者内部接口的描述。
常见方法 我们要学习的System类中的常见方法如下所示:
1 2 3 public static long currentTimeMillis () public static void exit (int status) public static native void arraycopy (Object src, int srcPos, Object dest, int destPos, int length) ;
接下来我们就来通过一些案例演示一下这些方法的特点。
演示currentTimeMillis 方法
1 2 3 4 5 6 7 8 9 10 11 12 13 public class SystemDemo01 { public static void main (String[] args) { long millis = System.currentTimeMillis(); System.out.println("当前时间所对应的毫秒值为:" + millis); } }
获取到当前时间的毫秒值的意义:我们常常来需要统计某一段代码的执行时间。此时我们就可以在执行这段代码之前获取一次时间,在执行完毕以后再次获取一次系统时间,然后计算两个时间的差值,
这个差值就是这段代码执行完毕以后所需要的时间。如下代码所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 public class SystemDemo2 { public static void main (String[] args) { long start = System.currentTimeMillis(); for (int i = 1 ; i <= 100000 ; i++) { boolean flag = isPrime2(i); if (flag) { System.out.println(i); } } long end = System.currentTimeMillis(); System.out.println(end - start); } public static boolean isPrime1 (int number) { for (int i = 2 ; i < number; i++) { if (number % i == 0 ) { return false ; } } return true ; } public static boolean isPrime2 (int number) { for (int i = 2 ; i <= Math.sqrt(number); i++) { if (number % i == 0 ) { return false ; } } return true ; } }
演示exit方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public class SystemDemo01 { public static void main (String[] args) { System.out.println("程序开始执行了....." ); System.exit(0 ); System.out.println("程序终止了.........." ); } }
演示arraycopy方法
方法参数说明:
1 2 3 4 5 6 public static native void arraycopy (Object src, int srcPos, Object dest, int destPos, int length) ;
代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public class SystemDemo01 { public static void main (String[] args) { int [] srcArray = {23 , 45 , 67 , 89 , 14 , 56 } ; int [] desArray = new int [10 ] ; System.arraycopy(srcArray , 0 , desArray , 1 , 3 ); for (int x = 0 ; x < desArray.length ; x++) { if (x != desArray.length - 1 ) { System.out.print(desArray[x] + ", " ); }else { System.out.println(desArray[x]); } } } }
使用这个方法我们也可以完成数组元素的删除操作,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public class SystemDemo02 { public static void main (String[] args) { int [] srcArray = {23 , 45 , 67 , 89 , 14 , 56 } ; System.arraycopy(srcArray , 3 , srcArray , 2 , 3 ); for (int x = 0 ; x < srcArray.length ; x++) { if (x != desArray.length - 1 ) { System.out.print(srcArray[x] + ", " ); }else { System.out.println(srcArray[x]); } } } }
通过控制台输出结果我们可以看到此时多出了一个56元素,此时我们只需要将最后一个位置设置为0即可。如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class SystemDemo02 { public static void main (String[] args) { int [] srcArray = {23 , 45 , 67 , 89 , 14 , 56 } ; System.arraycopy(srcArray , 3 , srcArray , 2 , 3 ); srcArray[srcArray.length - 1 ] = 0 ; for (int x = 0 ; x < srcArray.length ; x++) { if (x != srcArray.length - 1 ) { System.out.print(srcArray[x] + ", " ); }else { System.out.println(srcArray[x]); } } } }
此时我们可以看到元素”67”已经被删除掉了。67后面的其他元素依次向前进行移动了一位。
arraycopy方法底层细节:
如果数据源数组和目的地数组都是基本数据类型,那么两者的类型必须保持一致,否则会报错
在拷贝的时候需要考虑数组的长度,如果超出范围也会报错
如果数据源数组和目的地数组都是引用数据类型,那么子类类型可以赋值给父类类型
Runtime 概述 Runtime表示Java中运行时对象,可以获取到程序运行时设计到的一些信息
常见方法 我们要学习的Object类中的常见方法如下所示:
1 2 3 4 5 6 7 public static Runtime getRuntime () public void exit (int status) public int availableProcessors () public long maxMemory () public long totalMemory () public long freeMemory () public Process exec (String command)
代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 public class RunTimeDemo1 { public static void main (String[] args) throws IOException { System.out.println(Runtime.getRuntime().availableProcessors()); System.out.println(Runtime.getRuntime().maxMemory() / 1024 / 1024 ); System.out.println(Runtime.getRuntime().totalMemory() / 1024 / 1024 ); System.out.println(Runtime.getRuntime().freeMemory() / 1024 / 1024 ); Runtime.getRuntime().exec("shutdown -s -t 3600" ); } }
Object类 概述 Object类所在包是java.lang包。Object 是类层次结构的根,每个类都可以将 Object 作为超类。所有类都直接或者间接的继承自该类;换句话说,该类所具备的方法,其他所有类都继承了。
但是一般情况下我们很少去主动的创建Object类的对象,调用其对应的方法。更多的是创建Object类的某个子类对象,然后通过子类对象调用Object类中的方法。
常见方法 Object类中的常见方法如下所示:
1 2 3 public String toString () public boolean equals (Object obj) protected Object clone ()
演示toString方法
实现步骤:
创建一个学生类,提供两个成员变量(name ,age);并且提供对应的无参构造方法和有参构造方法以及get/set方法
创建一个测试类(ObjectDemo01),在测试类的main方法中去创建学生对象,然后调用该对象的toString方法获取该对象的字符串表现形式,并将结果进行输出
如下所示:
Student类
1 2 3 4 5 6 7 8 9 public class Student { private String name ; private String age ; ... }
ObjectDemo01测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public class ObjectDemo01 { public static void main (String[] args) { Student s1 = new Student ("itheima" , "14" ) ; String result1 = s1.toString(); System.out.println("s1对象的字符串表现形式为:" + result1); } }
其中getClass().getName()对应的结果就是:com.itheima.api.system.demo04.Student;Integer.toHexString(hashCode())对应的结果就是3f3afe78。
小结:
在通过输出语句输出一个对象时,默认调用的就是toString()方法
输出地址值一般没有意义,我们可以通过重写toString方法去输出对应的成员变量信息(快捷键:atl + insert , 空白处 右键 -> Generate -> 选择toString)
toString方法的作用:以良好的格式,更方便的展示对象中的属性值
一般情况下Jdk所提供的类都会重写Object类中的toString方法
演示equals方法
实现步骤:
在测试类(ObjectDemo02)的main方法中,创建两个学生对象,然后比较两个对象是否相同
代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class ObjectDemo02 { public static void main (String[] args) { Student s1 = new Student ("itheima" , "14" ) ; Student s2 = new Student ("itheima" , "14" ) ; System.out.println(s1 == s2); } }
因为”==”号比较的是对象的地址值,而我们通过new关键字创建了两个对象,它们的地址值是不相同的。因此比较结果就是false。
我们尝试调用Object类中的equals方法进行比较,代码如下所示:
1 2 3 4 5 boolean result = s1.equals(s2);System.out.println(result);
为什么结果还是false呢?我们可以查看一下Object类中equals方法的源码,如下所示:
1 2 3 public boolean equals (Object obj) { return (this == obj); }
通过源码我们可以发现默认情况下equals方法比较的也是对象的地址值。比较内存地址值一般情况下是没有意义的,我们希望比较的是对象的属性,如果两个对象的属性相同,我们认为就是同一个对象;
那么要比较对象的属性,我们就需要在Student类中重写Object类中的equals方法。e
小结:
默认情况下equals方法比较的是对象的地址值
比较对象的地址值是没有意义的,因此一般情况下我们都会重写Object类中的equals方法
对象克隆: 把A对象的属性值完全拷贝给B对象,也叫对象拷贝,对象复制
对象克隆的分类:
深克隆和浅克隆
浅克隆:
不管对象内部的属性是基本数据类型还是引用数据类型,都完全拷贝过来
基本数据类型拷贝过来的是具体的数据,引用数据类型拷贝过来的是地址值。
Object类默认的是浅克隆
深克隆:
基本数据类型拷贝过来,字符串复用,引用数据类型会重新创建新的
Objects类 概述 Objects类所在包是在java.util包下,因此在使用的时候需要进行导包。并且Objects类是被final修饰的,因此该类不能被继承。
Objects类提供了一些对象常见操作的方法。比如判断对象是否相等,判断对象是否为null等等。
我们可以发现Objects类中无无参构造方法,因此我们不能使用new关键字去创建Objects的对象。同时我们可以发现Objects类中所提供的方法都是静态的。因此我们可以通过类名直接去调用这些方法。
常见方法 我们要重点学习的Objects类中的常见方法如下所示:
1 2 3 4 public static String toString (Object o) public static boolean equals (Object a, Object b) public static boolean isNull (Object obj) public static boolean nonNull (Object obj)
我们要了解的Objects类中的常见方法如下所示:
1 2 3 public static <T> T requireNonNull (T obj) public static <T> T requireNonNullElse (T obj, T defaultObj) public static <T> T requireNonNullElseGet (T obj, Supplier<? extends T> supplier)
BigInteger类 引入 平时在存储整数的时候,Java中默认是int类型,int类型有取值范围:-2147483648 ~ 2147483647。如果数字过大,我们可以使用long类型,但是如果long类型也表示不下怎么办呢?
就需要用到BigInteger,可以理解为:大的整数。
有多大呢?理论上最大到42亿的21亿次方
基本上在内存撑爆之前,都无法达到这个上限。
概述 BigInteger所在包是在java.math包下,因此在使用的时候就需要进行导包。我们可以使用BigInteger类进行大整数的计算
常见方法 构造方法
1 2 3 4 5 6 public BigInteger (int num, Random rnd) public BigInteger (String val) public BigInteger (String val, int radix) 下面这个不是构造,而是一个静态方法获取BigInteger对象 public static BigInteger valueOf (long val)
构造方法小结:
如果BigInteger表示的数字没有超出long的范围,可以用静态方法获取。
如果BigInteger表示的超出long的范围,可以用构造方法获取。
对象一旦创建,BigInteger内部记录的值不能发生改变。
只要进行计算都会产生一个新的BigInteger对象
常见成员方法
BigDecimal类中使用最多的还是提供的进行四则运算的方法,如下:
1 2 3 4 5 6 7 8 9 public BigInteger add (BigInteger val) public BigInteger subtract (BigInteger val) public BigInteger multiply (BigInteger val) public BigInteger divide (BigInteger val) public BigInteger[] divideAndRemainder(BigInteger val) public boolean equals (Object x) public BigInteger pow (int exponent) public BigInteger max/min(BigInteger val) public int intValue (BigInteger val)
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 package com.itheima.a06bigintegerdemo;import java.math.BigInteger;public class BigIntegerDemo1 { public static void main (String[] args) { BigInteger bd4 = new BigInteger ("123" , 2 ); System.out.println(bd4); BigInteger bd5 = BigInteger.valueOf(16 ); BigInteger bd6 = BigInteger.valueOf(16 ); System.out.println(bd5 == bd6); BigInteger bd7 = BigInteger.valueOf(17 ); BigInteger bd8 = BigInteger.valueOf(17 ); System.out.println(bd7 == bd8); BigInteger bd9 = BigInteger.valueOf(1 ); BigInteger bd10 = BigInteger.valueOf(2 ); BigInteger result=bd9.add(bd10); System.out.println(result); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 package com.itheima.a06bigintegerdemo;import java.math.BigInteger;public class BigIntegerDemo2 { public static void main (String[] args) { BigInteger bd1 = BigInteger.valueOf(10 ); BigInteger bd2 = BigInteger.valueOf(5 ); BigInteger bd3 = bd1.add(bd2); System.out.println(bd3); BigInteger[] arr = bd1.divideAndRemainder(bd2); System.out.println(arr[0 ]); System.out.println(arr[1 ]); boolean result = bd1.equals(bd2); System.out.println(result); BigInteger bd4 = bd1.pow(2 ); System.out.println(bd4); BigInteger bd5 = bd1.max(bd2); BigInteger bd6 = BigInteger.valueOf(200 ); double v = bd6.doubleValue(); System.out.println(v); } }
底层存储方式: 对于计算机而言,其实是没有数据类型的概念的,都是0101010101,数据类型是编程语言自己规定的,所以在实际存储的时候,先把具体的数字变成二进制,每32个bit为一组,存储在数组中。
数组中最多能存储元素个数:21亿多
数组中每一位能表示的数字:42亿多
理论上,BigInteger能表示的最大数字为:42亿的21亿次方。
但是还没到这个数字,电脑的内存就会撑爆,所以一般认为BigInteger是无限的。
BigDecimal类 引入 首先我们来分析一下如下程序的执行结果:
1 2 3 4 5 6 7 public class BigDecimalDemo01 { public static void main (String[] args) { System.out.println(0.09 + 0.01 ); } }
这样的结果其实就是一个丢失精度的结果。
概述 BigDecimal所在包是在java.math包下,因此在使用的时候就需要进行导包。我们可以使用BigDecimal类进行更加精准的数据计算。
常见方法 BigDecimal类中使用最多的还是提供的进行四则运算的方法,如下:
1 2 3 4 public BigDecimal add (BigDecimal value) public BigDecimal subtract (BigDecimal value) public BigDecimal multiply (BigDecimal value) public BigDecimal divide (BigDecimal value)
接下来我们就来通过一些案例演示一下这些成员方法的使用。
演示基本的四则运算 代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class BigDecimalDemo01 { public static void main (String[] args) { BigDecimal b1 = new BigDecimal ("0.3" ) ; BigDecimal b2 = new BigDecimal ("4" ) ; System.out.println(b1.add(b2)); System.out.println(b1.subtract(b2)); System.out.println(b1.multiply(b2)); System.out.println(b1.divide(b2)); } }
运行程序进行测试,控制台输出结果如下:
演示除法的特殊情况
如果使用BigDecimal类型的数据进行除法运算的时候,得到的结果是一个无限循环小数,那么就会报错:ArithmeticException。 如下代码所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class BigDecimalDemo02 { public static void main (String[] args) { BigDecimal b1 = new BigDecimal ("1" ) ; BigDecimal b2 = new BigDecimal ("3" ) ; System.out.println(b1.divide(b2)); } }
运行程序进行测试,控制台输出结果如下所示:
1 2 3 Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. at java.base/java.math.BigDecimal.divide(BigDecimal.java:1716 ) at com.itheima.api.bigdecimal.demo02.BigDecimalDemo02.main(BigDecimalDemo02.java:14 )
针对这个问题怎么解决,此时我们就需要使用到BigDecimal类中另外一个divide方法,如下所示:
1 BigDecimal divide (BigDecimal divisor, int scale, int roundingMode)
上述divide方法参数说明:
divisor: 除数对应的BigDecimal对象; scale: 精确的位数; roundingMode: 取舍模式;
取舍模式被封装到了RoundingMode这个枚举类中(关于枚举我们后期再做重点讲解),在这个枚举类中定义了很多种取舍方式。最常见的取舍方式有如下几个: UP(直接进1) , FLOOR(直接删除) , HALF_UP(4舍五入),我们可以通过如下格式直接访问这些取舍模式:枚举类名.变量名
接下来我们就来演示一下这些取舍模式,代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 public class BigDecimalDemo02 { public static void main (String[] args) { method_03() ; } public static void method_03 () { BigDecimal b1 = new BigDecimal ("0.3" ) ; BigDecimal b2 = new BigDecimal ("4" ) ; System.out.println(b1.divide(b2 , 2 , RoundingMode.HALF_UP)); } public static void method_02 () { BigDecimal b1 = new BigDecimal ("1" ) ; BigDecimal b2 = new BigDecimal ("3" ) ; System.out.println(b1.divide(b2 , 2 , RoundingMode.FLOOR)); } public static void method_01 () { BigDecimal b1 = new BigDecimal ("1" ) ; BigDecimal b2 = new BigDecimal ("3" ) ; System.out.println(b1.divide(b2 , 2 , RoundingMode.UP)); } }
小结:后期在进行两个数的除法运算的时候,我们常常使用的是可以设置取舍模式的divide方法。
正则表达式 正则表达式的概念及演示
在Java中,经常需要验证一些字符串,例如:年龄必须是2位的数字、用户名必须是8位长度而且只能包含大小写字母、数字等。正则表达式就是用来验证各种字符串的规则。它内部描述了一些规则,我们可以验证用户输入的字符串是否匹配这个规则。
先看一个不使用正则表达式验证的例子:下面的程序让用户输入一个QQ号码,我们要验证:
QQ号码必须是5–15位长度
而且必须全部是数字
而且首位不能为0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 package com.itheima.a08regexdemo;public class RegexDemo1 { public static void main (String[] args) { String qq = "1234567890" ; System.out.println(checkQQ(qq)); System.out.println(qq.matches("[1-9]\\d{5,19}" )); } public static boolean checkQQ (String qq) { int len = qq.length(); if (len < 6 || len > 20 ) { return false ; } if (qq.startsWith("0" )) { return false ; } for (int i = 0 ; i < qq.length(); i++) { char c = qq.charAt(i); if (c < '0' | c > '9' ) { return false ; } } return true ; } }
1 2 3 4 5 6 public class Demo { public static void main (String[] args) { String qq = "1234567890" ; System.out.println(qq.matches("[1-9]\\d{5,19}" )); } }
正则表达式-字符类
[abc]:代表a或者b,或者c字符中的一个。
[^abc]:代表除a,b,c以外的任何字符。
[a-z]:代表a-z的所有小写字符中的一个。
[A-Z]:代表A-Z的所有大写字符中的一个。
[0-9]:代表0-9之间的某一个数字字符。
[a-zA-Z0-9]:代表a-z或者A-Z或者0-9之间的任意一个字符。
[a-dm-p]:a 到 d 或 m 到 p之间的任意一个字符。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 package com.itheima.a08regexdemo;public class RegexDemo2 { public static void main (String[] args) { System.out.println("-----------1-------------" ); System.out.println("a" .matches("[abc]" )); System.out.println("z" .matches("[abc]" )); System.out.println("-----------2-------------" ); System.out.println("a" .matches("[^abc]" )); System.out.println("z" .matches("[^abc]" )); System.out.println("zz" .matches("[^abc]" )); System.out.println("zz" .matches("[^abc][^abc]" )); System.out.println("-----------3-------------" ); System.out.println("a" .matches("[a-zA-z]" )); System.out.println("z" .matches("[a-zA-z]" )); System.out.println("aa" .matches("[a-zA-z]" )); System.out.println("zz" .matches("[a-zA-Z]" )); System.out.println("zz" .matches("[a-zA-Z][a-zA-Z]" )); System.out.println("0" .matches("[a-zA-Z]" )); System.out.println("0" .matches("[a-zA-Z0-9]" )); System.out.println("-----------4-------------" ); System.out.println("a" .matches("[a-d[m-p]]" )); System.out.println("d" .matches("[a-d[m-p]]" )); System.out.println("m" .matches("[a-d[m-p]]" )); System.out.println("p" .matches("[a-d[m-p]]" )); System.out.println("e" .matches("[a-d[m-p]]" )); System.out.println("0" .matches("[a-d[m-p]]" )); System.out.println("----------5------------" ); System.out.println("a" .matches("[a-z&[def]]" )); System.out.println("d" .matches("[a-z&&[def]]" )); System.out.println("0" .matches("[a-z&&[def]]" )); System.out.println("-----------6------------_" ); System.out.println("a" .matches("[a-z&&[^bc]]" )); System.out.println("b" .matches("[a-z&&[^bc]]" )); System.out.println("0" .matches("[a-z&&[^bc]]" )); System.out.println("-----------7-------------" ); System.out.println("a" .matches("[a-z&&[^m-p]]" )); System.out.println("m" .matches("[a-z&&[^m-p]]" )); System.out.println("0" .matches("[a-z&&[^m-p]]" )); } }
正则表达式-逻辑运算符
语法示例:
&&:并且
| :或者
\ :转义字符
代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class Demo { public static void main (String[] args) { String str = "had" ; String regex = "[a-z&&[^aeiou]]ad" ; System.out.println("1." + str.matches(regex)); regex = "[a|e|i|o|u]ad" ; System.out.println("2." + str.matches(regex)); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 package com.itheima.a08regexdemo;public class RegexDemo3 { public static void main (String[] args) { System.out.println("\"" ); System.out.println("c:Users\\moon\\IdeaProjects\\basic-code\\myapi\\src\\com\\itheima\\a08regexdemo\\RegexDemo1.java" ); } }
正则表达式-预定义字符
语法示例:
“.” : 匹配任何字符。
“\d”:任何数字[0-9]的简写;
“\D”:任何非数字[^0-9]的简写;
“\s”: 空白字符:[ \t\n\x0B\f\r] 的简写
“\S”: 非空白字符:[^\s] 的简写
“\w”:单词字符:[a-zA-Z_0-9]的简写
“\W”:非单词字符:[^\w]
代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 public class Demo { public static void main (String[] args) { System.out.println("你" .matches(".." )); System.out.println("你" .matches("." )); System.out.println("你a" .matches(".." )); System.out.println("a" .matches("\\d" )); System.out.println("3" .matches("\\d" )); System.out.println("333" .matches("\\d" )); System.out.println("z" .matches("\\w" )); System.out.println("2" .matches("\\w" )); System.out.println("21" .matches("\\w" )); System.out.println("你" .matches("\\w" )); System.out.println("你" .matches("\\W" )); System.out.println("---------------------------------------------" ); System.out.println("2442fsfsf" .matches("\\w{6,}" )); System.out.println("244f" .matches("\\w{6,}" )); System.out.println("23dF" .matches("[a-zA-Z0-9]{4}" )); System.out.println("23 F" .matches("[a-zA-Z0-9]{4}" )); System.out.println("23dF" .matches("[\\w&&[^_]]{4}" )); System.out.println("23_F" .matches("[\\w&&[^_]]{4}" )); } }
正则表达式-数量词
语法示例:
X? : 0次或1次
X* : 0次到多次
X+ : 1次或多次
X{n} : 恰好n次
X{n,} : 至少n次
X{n,m}: n到m次(n和m都是包含的)
代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 public class Demo { public static void main (String[] args) { System.out.println("2442fsfsf" .matches("\\w{6,}" )); System.out.println("244f" .matches("\\w{6,}" )); System.out.println("23dF" .matches("[a-zA-Z0-9]{4}" )); System.out.println("23 F" .matches("[a-zA-Z0-9]{4}" )); System.out.println("23dF" .matches("[\\w&&[^_]]{4}" )); System.out.println("23_F" .matches("[\\w&&[^_]]{4}" )); } }
本地数据爬取 Pattern:表示正则表达式 Matcher:文本匹配器,作用按照正则表达式的规则去读取字符串,从头开始读取。 在大串中去找符合匹配规则的子串。
代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 package com.itheima.a08regexdemo;import java.util.regex.Matcher;import java.util.regex.Pattern;public class RegexDemo6 { public static void main (String[] args) { String str = "Java自从95年问世以来,经历了很多版本,目前企业中用的最多的是Java8和Java11," + "因为这两个是长期支持版本,下一个长期支持版本是Java17,相信在未来不久Java17也会逐渐登上历史舞台" ; Pattern p = Pattern.compile("Java\\d{0,2}" ); Matcher m = p.matcher(str); while (m.find()) { String s = m.group(); System.out.println(s); } } private static void method1 (String str) { Pattern p = Pattern.compile("Java\\d{0,2}" ); Matcher m = p.matcher(str); boolean b = m.find(); String s1 = m.group(); System.out.println(s1); b = m.find(); String s2 = m.group(); System.out.println(s2); } }
贪婪爬取和非贪婪爬取 1 2 3 4 5 6 7 8 9 10 只写+和表示贪婪匹配,如果在+和后面加问号表示非贪婪爬取 +? 非贪婪匹配 *? 非贪婪匹配 贪婪爬取:在爬取数据的时候尽可能的多获取数据 非贪婪爬取:在爬取数据的时候尽可能的少获取数据 举例: 如果获取数据:ab+ 贪婪爬取获取结果:abbbbbbbbbbbb 非贪婪爬取获取结果:ab
代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 public class RegexDemo10 { public static void main (String[] args) { String s = "Java自从95年问世以来,abbbbbbbbbbbbaaaaaaaaaaaaaaaaaa" + "经历了很多版木,目前企业中用的最多的是]ava8和]ava11,因为这两个是长期支持版木。" + "下一个长期支持版本是Java17,相信在未来不久Java17也会逐渐登上历史舞台" ; String regex = "ab+" ; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(s); while (m.find()) { System.out.println(m.group()); } } }
String的split方法中使用正则表达式
String类的split()方法原型:
1 2 public String[] split(String regex)
代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 String s = "小诗诗dqwefqwfqwfwq12312小丹丹dqwefqwfqwfwq12312小惠惠" ;String[] arr = s.split("[\\w&&[^_]]+" ); for (int i = 0 ; i < arr.length; i++) { System.out.println(arr[i]); }
String类的replaceAll方法中使用正则表达式
String类的replaceAll()方法原型:
1 2 public String replaceAll (String regex,String newStr)
1 2 3 4 5 6 7 8 9 10 11 String s = "小诗诗dqwefqwfqwfwq12312小丹丹dqwefqwfqwfwq12312小惠惠" ;String result1 = s.replaceAll("[\\w&&[^_]]+" , "vs" );System.out.println(result1);
正则表达式-分组括号( ) 细节:如何识别组号?
只看左括号,不看有括号,按照左括号的顺序,从左往右,依次为第一组,第二组,第三组等等
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 String regex1 = "(.).+\\1" ;System.out.println("a123a" .matches(regex1)); System.out.println("b456b" .matches(regex1)); System.out.println("17891" .matches(regex1)); System.out.println("&abc&" .matches(regex1)); System.out.println("a123b" .matches(regex1)); System.out.println("--------------------------" ); String regex2 = "(.+).+\\1" ;System.out.println("abc123abc" .matches(regex2)); System.out.println("b456b" .matches(regex2)); System.out.println("123789123" .matches(regex2)); System.out.println("&!@abc&!@" .matches(regex2)); System.out.println("abc123abd" .matches(regex2)); System.out.println("---------------------" ); String regex3 = "((.)\\2*).+\\1" ;System.out.println("aaa123aaa" .matches(regex3)); System.out.println("bbb456bbb" .matches(regex3)); System.out.println("111789111" .matches(regex3)); System.out.println("&&abc&&" .matches(regex3)); System.out.println("aaa123aab" .matches(regex3));
分组练习 需求:
将字符串:我要学学编编编编程程程程程程。
替换为:我要学编程
1 2 3 4 5 6 7 8 9 10 11 12 String str = "我要学学编编编编程程程程程程" ;String result = str.replaceAll("(.)\\1+" , "$1" );System.out.println(result);
忽略大小写的写法 1 2 3 4 5 6 7 String regex = "(?i)abc" ;String regex = "a(?i)bc" ;String regex = "a((?i)b)c" ;
非捕获分组 非捕获分组:分组之后不需要再用本组数据,仅仅是把数据括起来。
1 2 3 4 5 6 7 8 9 10 11 12 String regex2 = "[1-9]\\d{16}(\\d Xx)\\1" ;System.out.println("41080119930228457x" .matches(regex2));
Date类 Date概述 java.util.Date`类 表示特定的瞬间,精确到毫秒。
继续查阅Date类的描述,发现Date拥有多个构造函数,只是部分已经过时,我们重点看以下两个构造函数
public Date()
:从运行程序的此时此刻到时间原点经历的毫秒值,转换成Date对象,分配Date对象并初始化此对象,以表示分配它的时间(精确到毫秒)。
public Date(long date)
:将指定参数的毫秒值date,转换成Date对象,分配Date对象并初始化此对象,以表示自从标准基准时间(称为“历元(epoch)”,即1970年1月1日00:00:00 GMT)以来的指定毫秒数。
tips: 由于中国处于东八区(GMT+08:00)是比世界协调时间/格林尼治时间(GMT)快8小时的时区,当格林尼治标准时间为0:00时,东八区的标准时间为08:00。
简单来说:使用无参构造,可以自动设置当前系统时间的毫秒时刻;指定long类型的构造参数,可以自定义毫秒时刻。例如:
1 2 3 4 5 6 7 8 9 10 import java.util.Date;public class Demo01Date { public static void main (String[] args) { System.out.println(new Date ()); System.out.println(new Date (0L )); } }
tips:在使用println方法时,会自动调用Date类中的toString方法。Date类对Object类中的toString方法进行了覆盖重写,所以结果为指定格式的字符串。
Date常用方法 Date类中的多数方法已经过时,常用的方法有:
public long getTime()
把日期对象转换成对应的时间毫秒值。
public void setTime(long time)
把方法参数给定的毫秒值设置给日期对象
示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class DateDemo02 { public static void main (String[] args) { Date d = new Date (); long time = System.currentTimeMillis(); d.setTime(time); System.out.println(d); } }
小结:Date表示特定的时间瞬间,我们可以使用Date对象对时间进行操作。
java.text.SimpleDateFormat
是日期/时间格式化类,我们通过这个类可以帮我们完成日期和文本之间的转换,也就是可以在Date对象与String对象之间进行来回转换。
格式化 :按照指定的格式,把Date对象转换为String对象。
解析 :按照指定的格式,把String对象转换为Date对象。
构造方法 由于DateFormat为抽象类,不能直接使用,所以需要常用的子类java.text.SimpleDateFormat
。这个类需要一个模式(格式)来指定格式化或解析的标准。构造方法为:
public SimpleDateFormat(String pattern)
:用给定的模式和默认语言环境的日期格式符号构造SimpleDateFormat。参数pattern是一个字符串,代表日期时间的自定义格式。
格式规则 常用的格式规则为:
标识字母(区分大小写)
含义
y
年
M
月
d
日
H
时
m
分
s
秒
备注:更详细的格式规则,可以参考SimpleDateFormat类的API文档。
常用方法 DateFormat类的常用方法有:
小结:DateFormat可以将Date对象和字符串相互转换。
Calendar类 概述
java.util.Calendar类表示一个“日历类”,可以进行日期运算。它是一个抽象类,不能创建对象,我们可以使用它的子类:java.util.GregorianCalendar类。
有两种方式可以获取GregorianCalendar对象:
直接创建GregorianCalendar对象;
通过Calendar的静态方法getInstance()方法获取GregorianCalendar对象
常用方法
方法名
说明
public static Calendar getInstance()
获取一个它的子类GregorianCalendar对象。
public int get(int field)
获取某个字段的值。field参数表示获取哪个字段的值, 可以使用Calender中定义的常量来表示: Calendar.YEAR : 年 Calendar.MONTH :月 Calendar.DAY_OF_MONTH:月中的日期 Calendar.HOUR:小时 Calendar.MINUTE:分钟 Calendar.SECOND:秒 Calendar.DAY_OF_WEEK:星期
public void set(int field,int value)
设置某个字段的值
public void add(int field,int amount)
为某个字段增加/减少指定的值
get方法示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 public class Demo { public static void main (String[] args) { Calendar instance = Calendar.getInstance(); System.out.println(instance); int year = instance.get(Calendar.YEAR); int month = instance.get(Calendar.MONTH) + 1 ; int day = instance.get(Calendar.DAY_OF_MONTH); int hour = instance.get(Calendar.HOUR); int minute = instance.get(Calendar.MINUTE); int second = instance.get(Calendar.SECOND); int week = instance.get(Calendar.DAY_OF_WEEK); System.out.println(year + "年" + month + "月" + day + "日" + hour + ":" + minute + ":" + second); System.out.println(getWeek(week)); } public static String getWeek (int w) { String[] weekArray = {"星期日" , "星期一" , "星期二" , "星期三" , "星期四" , "星期五" , "星期六" }; return weekArray[w - 1 ]; } }
set方法示例: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public class Demo { public static void main (String[] args) { Calendar c1 = Calendar.getInstance(); c1.set(Calendar.YEAR, 1998 ); c1.set(Calendar.MONTH, 3 - 1 ); c1.set(Calendar.DAY_OF_MONTH, 18 ); int w = c1.get(Calendar.DAY_OF_WEEK); System.out.println("班长出生那天是:" + getWeek(w)); } public static String getWeek (int w) { String[] weekArray = {"星期日" , "星期一" , "星期二" , "星期三" , "星期四" , "星期五" , "星期六" }; return weekArray[w - 1 ]; } }
add方法示例: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public class Demo { public static void main (String[] args) { Calendar c2 = Calendar.getInstance(); c2.add(Calendar.DAY_OF_MONTH, 200 ); int y = c2.get(Calendar.YEAR); int m = c2.get(Calendar.MONTH) + 1 ; int d = c2.get(Calendar.DAY_OF_MONTH); int wk = c2.get(Calendar.DAY_OF_WEEK); System.out.println("200天后是:" + y + "年" + m + "月" + d + "日" + getWeek(wk)); } public static String getWeek (int w) { String[] weekArray = {"星期日" , "星期一" , "星期二" , "星期三" , "星期四" , "星期五" , "星期六" }; return weekArray[w - 1 ]; } }
JDK8时间相关类
JDK8时间类类名
作用
ZoneId
时区
Instant
时间戳
ZoneDateTime
带时区的时间
DateTimeFormatter
用于时间的格式化和解析
LocalDate
年、月、日
LocalTime
时、分、秒
LocalDateTime
年、月、日、时、分、秒
Duration
时间间隔(秒,纳,秒)
Period
时间间隔(年,月,日)
ChronoUnit
时间间隔(所有单位)
ZoneId 时区 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Set<String> zoneIds = ZoneId.getAvailableZoneIds(); System.out.println(zoneIds.size()); System.out.println(zoneIds); ZoneId zoneId = ZoneId.systemDefault();System.out.println(zoneId); ZoneId zoneId1 = ZoneId.of("Asia/Pontianak" );System.out.println(zoneId1);
Instant 时间戳 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 Instant now = Instant.now();System.out.println(now); Instant instant1 = Instant.ofEpochMilli(0L );System.out.println(instant1); Instant instant2 = Instant.ofEpochSecond(1L );System.out.println(instant2); Instant instant3 = Instant.ofEpochSecond(1L , 1000000000L );System.out.println(instant3); ZonedDateTime time = Instant.now().atZone(ZoneId.of("Asia/Shanghai" ));System.out.println(time); Instant instant4=Instant.ofEpochMilli(0L ); Instant instant5 = Instant.ofEpochMilli(1000L );boolean result1=instant4.isBefore(instant5);System.out.println(result1); boolean result2 = instant4.isAfter(instant5);System.out.println(result2); Instant instant6 = Instant.ofEpochMilli(3000L );System.out.println(instant6); Instant instant7 = instant6.minusSeconds(1 );System.out.println(instant7);
ZoneDateTime 带时区的时间 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 ZonedDateTime now = ZonedDateTime.now();System.out.println(now); ZonedDateTime time1 = ZonedDateTime.of(2023 , 10 , 1 , 11 , 12 , 12 , 0 , ZoneId.of("Asia/Shanghai" )); System.out.println(time1); Instant instant = Instant.ofEpochMilli(0L );ZoneId zoneId = ZoneId.of("Asia/Shanghai" );ZonedDateTime time2 = ZonedDateTime.ofInstant(instant, zoneId);System.out.println(time2); ZonedDateTime time3 = time2.withYear(2000 );System.out.println(time3); ZonedDateTime time4 = time3.minusYears(1 );System.out.println(time4); ZonedDateTime time5 = time4.plusYears(1 );System.out.println(time5);
1 2 3 4 5 6 7 8 9 10 11 ZonedDateTime time = Instant.now().atZone(ZoneId.of("Asia/Shanghai" ));DateTimeFormatter dtf1=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm;ss EE a" ); System.out.println(dtf1.format(time));
LocalDate 年、月、日 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 LocalDate nowDate = LocalDate.now();LocalDate ldDate = LocalDate.of(2023 , 1 , 1 );System.out.println("指定日期:" + ldDate); System.out.println("=============================" ); int year = ldDate.getYear();System.out.println("year: " + year); Month m = ldDate.getMonth();System.out.println(m); System.out.println(m.getValue()); int month = ldDate.getMonthValue();System.out.println("month: " + month); int day = ldDate.getDayOfMonth();System.out.println("day:" + day); int dayofYear = ldDate.getDayOfYear();System.out.println("dayOfYear:" + dayofYear); DayOfWeek dayOfWeek = ldDate.getDayOfWeek();System.out.println(dayOfWeek); System.out.println(dayOfWeek.getValue()); System.out.println(ldDate.isBefore(ldDate)); System.out.println(ldDate.isAfter(ldDate)); LocalDate withLocalDate = ldDate.withYear(2000 );System.out.println(withLocalDate); LocalDate minusLocalDate = ldDate.minusYears(1 );System.out.println(minusLocalDate); LocalDate plusLocalDate = ldDate.plusDays(1 );System.out.println(plusLocalDate); LocalDate birDate = LocalDate.of(2000 , 1 , 1 );LocalDate nowDate1 = LocalDate.now();MonthDay birMd = MonthDay.of(birDate.getMonthValue(), birDate.getDayOfMonth());MonthDay nowMd = MonthDay.from(nowDate1);System.out.println("今天是你的生日吗? " + birMd.equals(nowMd));
LocalTime 时、分、秒 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 LocalTime nowTime = LocalTime.now();System.out.println("今天的时间:" + nowTime); int hour = nowTime.getHour();System.out.println("hour: " + hour); int minute = nowTime.getMinute();System.out.println("minute: " + minute); int second = nowTime.getSecond();System.out.println("second:" + second); int nano = nowTime.getNano();System.out.println("nano:" + nano); System.out.println("------------------------------------" ); System.out.println(LocalTime.of(8 , 20 )); System.out.println(LocalTime.of(8 , 20 , 30 )); System.out.println(LocalTime.of(8 , 20 , 30 , 150 )); LocalTime mTime = LocalTime.of(8 , 20 , 30 , 150 );System.out.println(nowTime.isBefore(mTime)); System.out.println(nowTime.isAfter(mTime)); System.out.println(nowTime.withHour(10 )); System.out.println(nowTime.plusHours(10 ));
LocalDateTime 年、月、日、时、分、秒 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 LocalDateTime nowDateTime = LocalDateTime.now();System.out.println("今天是:" + nowDateTime); System.out.println(nowDateTime.getYear()); System.out.println(nowDateTime.getMonthValue()); System.out.println(nowDateTime.getDayOfMonth()); System.out.println(nowDateTime.getHour()); System.out.println(nowDateTime.getMinute()); System.out.println(nowDateTime.getSecond()); System.out.println(nowDateTime.getNano()); System.out.println("dayofYear:" + nowDateTime.getDayOfYear()); System.out.println(nowDateTime.getDayOfWeek()); System.out.println(nowDateTime.getDayOfWeek().getValue()); System.out.println(nowDateTime.getMonth()); System.out.println(nowDateTime.getMonth().getValue()); LocalDate ld = nowDateTime.toLocalDate();System.out.println(ld); LocalTime lt = nowDateTime.toLocalTime();System.out.println(lt.getHour()); System.out.println(lt.getMinute()); System.out.println(lt.getSecond());
Duration 时间间隔(秒,纳,秒) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 LocalDateTime today = LocalDateTime.now();System.out.println(today); LocalDateTime birthDate = LocalDateTime.of(2000 , 1 , 1 , 0 , 0 , 0 );System.out.println(birthDate); Duration duration = Duration.between(birthDate, today);System.out.println("相差的时间间隔对象:" + duration); System.out.println("============================================" ); System.out.println(duration.toDays()); System.out.println(duration.toHours()); System.out.println(duration.toMinutes()); System.out.println(duration.toMillis()); System.out.println(duration.toNanos());
Period 时间间隔(年,月,日) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 LocalDate today = LocalDate.now();System.out.println(today); LocalDate birthDate = LocalDate.of(2000 , 1 , 1 );System.out.println(birthDate); Period period = Period.between(birthDate, today);System.out.println("相差的时间间隔对象:" + period); System.out.println(period.getYears()); System.out.println(period.getMonths()); System.out.println(period.getDays()); System.out.println(period.toTotalMonths());
ChronoUnit 时间间隔(所有单位) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 LocalDateTime today = LocalDateTime.now();System.out.println(today); LocalDateTime birthDate = LocalDateTime.of(2000 , 1 , 1 ,0 , 0 , 0 );System.out.println(birthDate); System.out.println("相差的年数:" + ChronoUnit.YEARS.between(birthDate, today)); System.out.println("相差的月数:" + ChronoUnit.MONTHS.between(birthDate, today)); System.out.println("相差的周数:" + ChronoUnit.WEEKS.between(birthDate, today)); System.out.println("相差的天数:" + ChronoUnit.DAYS.between(birthDate, today)); System.out.println("相差的时数:" + ChronoUnit.HOURS.between(birthDate, today)); System.out.println("相差的分数:" + ChronoUnit.MINUTES.between(birthDate, today)); System.out.println("相差的秒数:" + ChronoUnit.SECONDS.between(birthDate, today)); System.out.println("相差的毫秒数:" + ChronoUnit.MILLIS.between(birthDate, today)); System.out.println("相差的微秒数:" + ChronoUnit.MICROS.between(birthDate, today)); System.out.println("相差的纳秒数:" + ChronoUnit.NANOS.between(birthDate, today)); System.out.println("相差的半天数:" + ChronoUnit.HALF_DAYS.between(birthDate, today)); System.out.println("相差的十年数:" + ChronoUnit.DECADES.between(birthDate, today)); System.out.println("相差的世纪(百年)数:" + ChronoUnit.CENTURIES.between(birthDate, today)); System.out.println("相差的千年数:" + ChronoUnit.MILLENNIA.between(birthDate, today)); System.out.println("相差的纪元数:" + ChronoUnit.ERAS.between(birthDate, today));
包装类 概述 Java提供了两个类型系统,基本类型与引用类型,使用基本类型在于效率,然而很多情况,会创建对象使用,因为对象可以做更多的功能,如果想要我们的基本类型像对象一样操作,就可以使用基本类型对应的包装类,如下:
基本类型
对应的包装类(位于java.lang包中)
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
char
Character
boolean
Boolean
Integer类
Integer类概述
包装一个对象中的原始类型 int 的值
Integer类构造方法及静态方法
方法名
说明
public Integer(int value)
根据 int 值创建 Integer 对象(过时)
public Integer(String s)
根据 String 值创建 Integer 对象(过时)
public static Integer valueOf(int i)
返回表示指定的 int 值的 Integer 实例
public static Integer valueOf(String s)
返回保存指定String值的 Integer 对象
static string tobinarystring(int i)
得到二进制
static string tooctalstring(int i)
得到八进制
static string toHexstring(int i)
得到十六进制
static int parseInt(string s)
将字符串类型的整数转成int类型的整数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 Integer i1 = new Integer (100 );System.out.println(i1); Integer i2 = new Integer ("100" );System.out.println(i2); System.out.println("--------" ); Integer i3 = Integer.valueOf(100 );System.out.println(i3); Integer i4 = Integer.valueOf("100" );System.out.println(i4);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 String str1 = Integer.toBinaryString(100 );System.out.println(str1); String str2 = Integer.toOctalString(100 );System.out.println(str2); String str3 = Integer.toHexString(100 );System.out.println(str3); int i = Integer.parseInt("123" );System.out.println(i); System.out.println(i + 1 ); String str = "true" ;boolean b = Boolean.parseBoolean(str);System.out.println(b);
装箱与拆箱 基本类型与对应的包装类对象之间,来回转换的过程称为”装箱“与”拆箱“:
装箱 :从基本类型转换为对应的包装类对象。
拆箱 :从包装类对象转换为对应的基本类型。
用Integer与 int为例:(看懂代码即可)
基本数值—->包装对象
1 2 Integer i = new Integer (4 );Integer iii = Integer.valueOf(4 );
包装对象—->基本数值
自动装箱与自动拆箱 由于我们经常要做基本类型与包装类之间的转换,从Java 5(JDK 1.5)开始,基本类型与包装类的装箱、拆箱动作可以自动完成。例如:
1 2 3 Integer i = 4 ;i = i + 5 ;
基本类型与字符串之间的转换 基本类型转换为String
转换方式
方式一:直接在数字后加一个空字符串
方式二:通过String类静态方法valueOf()
示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class IntegerDemo { public static void main (String[] args) { int number = 100 ; String s1 = number + "" ; System.out.println(s1); String s2 = String.valueOf(number); System.out.println(s2); System.out.println("--------" ); } }
String转换成基本类型 除了Character类之外,其他所有包装类都具有parseXxx静态方法可以将字符串参数转换为对应的基本类型:
public static byte parseByte(String s)
:将字符串参数转换为对应的byte基本类型。
public static short parseShort(String s)
:将字符串参数转换为对应的short基本类型。
public static int parseInt(String s)
:将字符串参数转换为对应的int基本类型。
public static long parseLong(String s)
:将字符串参数转换为对应的long基本类型。
public static float parseFloat(String s)
:将字符串参数转换为对应的float基本类型。
public static double parseDouble(String s)
:将字符串参数转换为对应的double基本类型。
public static boolean parseBoolean(String s)
:将字符串参数转换为对应的boolean基本类型。
代码使用(仅以Integer类的静态方法parseXxx为例)如:
转换方式
方式一:先将字符串数字转成Integer,再调用valueOf()方法
方式二:通过Integer静态方法parseInt()进行转换
示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class IntegerDemo { public static void main (String[] args) { String s = "100" ; Integer i = Integer.valueOf(s); int x = i.intValue(); System.out.println(x); int y = Integer.parseInt(s); System.out.println(y); } }
注意:如果字符串参数的内容无法正确转换为对应的基本类型,则会抛出java.lang.NumberFormatException
异常。
底层原理 建议:获取Integer对象的时候不要自己new,而是采取直接赋值或者静态方法valueOf的方式
因为在实际开发中,-128~127之间的数据,用的比较多。如果每次使用都是new对象,那么太浪费内存了。
所以,提前把这个范围之内的每一个数据都创建好对象,如果要用到了不会创建新的,而是返回已经创建好的对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 Integer i3 = Integer.valueOf(123 );Integer i4 = Integer.valueOf("123" );Integer i5 = Integer.valueOf("123" , 8 );System.out.println(i3); System.out.println(i4); System.out.println(i5); Integer i6 = Integer.valueOf(127 );Integer i7 = Integer.valueOf(127 );System.out.println(i6 == i7); Integer i8 = Integer.valueOf(128 );Integer i9 = Integer.valueOf(128 );System.out.println(i8 == i9);