java -- 自动拆装箱 && 正则表达式

自动拆装箱

基本概念

自动拆装箱是jdk-1.5引入的新特性,目的是为了简化包装类与对应基本数据类型之间的相互转化,这点有点类似java值类型的自动转换。举例如下:

1
2
3
4
5
//在java中我们可以进行如下赋值(自动装箱)
Integer i = 1;

//而实际上,java底层为我们完成了如下操作:
Integer i = new Integer(1);
1
2
3
4
5
6
//也可以进行如下算术运算(自动拆箱)
Integer i = new Integer(1);
int j = i + 1;

//实际上,java会将i自动转换为int
int j = i.intValue() + 1;

面试中相关问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Main {
public static void main(String[] args) {

Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 200;
Integer i4 = 200;

System.out.println(i1==i2);
System.out.println(i3==i4);
}
}

输出结果:
true
//这里比较的是两个对象内存地址是否一样,因为Integer自动装箱的缓存机制([-128,127]),所以100自动装箱,指向的是同一个对象。

false
//由于200已经超出[-128,127]范围,故重新new了两个对象,地址不一致
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Main {
public static void main(String[] args) {

Double i1 = 100.0;
Double i2 = 100.0;
Double i3 = 200.0;
Double i4 = 200.0;

System.out.println(i1==i2);
System.out.println(i3==i4);
}
}

输出结果:
false
false
//因为Double中不存在像Integer那样的缓存机制
//总结:
//Integer、Short、Byte、Character、Long这几个类的valueOf方法的实现是类似的(存在缓存)
//Double、Float的valueOf方法的实现是类似的(不存在缓存)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Main {
public static void main(String[] args) {

Boolean i1 = false;
Boolean i2 = false;
Boolean i3 = true;
Boolean i4 = true;

System.out.println(i1==i2);
System.out.println(i3==i4);
}
}

输出结果:
true
true
//Boolean的自动装箱,生成的对象都是预先定义好的静态成员变量,如下:
public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
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 Main {
public static void main(String[] args) {

Integer a = 1;
Integer b = 2;
Integer c = 3;
Integer d = 3;
Integer e = 321;
Integer f = 321;
Long g = 3L;
Long h = 2L;

System.out.println(c==d);
System.out.println(e==f);
System.out.println(c==(a+b));
System.out.println(c.equals(a+b));
System.out.println(g==(a+b));
System.out.println(g.equals(a+b));
System.out.println(g.equals(a+h));
}
}


//这里对双目运算符“==”总结如下:
1.当“==”两端是同一数据类型时:若都为类类型,则比较地址;若都为值类型,则比较数值大小
2.当“==”两端数据类型不一致时:将“类类型”拆箱为“值类型”,即Integer转为int
//对“+”、“-”、“*”、“/”算术运算符总结如下:
所有“类类型”统一转为“值类型”(统一拆箱)参与运算
//对equals()总结如下:
满足2点,才返回true
1.数据类型一致(由于equals中形参类型是Object,若传入基本数据类型,会自动装箱,int—>Integer double -> Double,以此类推)
2.value相等

输出为:
true
false
true
true
true
false
true

正则表达式

什么是正则表达式

可以简单的理解为:一种用于检测给定字符串是否满足特定规则的表达式

常用正则表达式

正则表达式匹配规则
x字符x
\反斜线字符
[abc]a、b或c
[^abc]除了a、b和c以外的任何字符
[a-zA-Z]a 到 z 或 A 到 Z(两头字母包含在内)
.任何字符(与行结束符可能匹配也可能不匹配)
\d 或 [0-9]数字
\D 或 [ ^0-9 ]非数字
\s 或 [\t\n\x0B\f\r]空白字符
\S 或 [ ^\s ]非空白字符
\w 或 [a-zA-Z_0-9]单词字符
\W 或 [ ^\w ]非单词字符
X?X,一次或一次也没有
X*X,零次或多次
X+X,一次或多次
X{n}X,恰好n次
X{n, }X,至少n次
X{n,m}X,至少n次,但是不超过m次

使用

一般在String的成员函数matches(String regex) 中使用,例如:

1
2
3
String QQ = "12345678";
//要求QQ不能以零开头,只能包含数字,位数不少于5不大于15;
boolean isValid = QQ.matches("[1-9][0-9]{4,14}")