Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2b77260
commit 32a8666
Showing
3 changed files
with
111 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
# JAVA源码解析 | ||
|
||
## 基础 | ||
|
||
### String | ||
|
||
- String不可变的原因 | ||
|
||
String内部是实现byte数组实现的 | ||
|
||
```java | ||
private final byte[] value; | ||
``` | ||
|
||
并且这个数组一旦赋上值,就无法再修改这个数组的引用了,同时String封装的很好,没有提供外部公开接口能直接操作这个数组,并且String类为final的,保证不会被继承,方法也不会被覆写,所以**String不可变** | ||
|
||
- equals原理 | ||
|
||
```java | ||
if (this == obj){ | ||
return true; | ||
} | ||
if (obj instanceof String){ | ||
if (this.value.length == obj.value.length){ | ||
for(0...obj.length){ | ||
if (this.value[i] != obj.value[i]){ | ||
return false; | ||
} | ||
} | ||
} | ||
} | ||
return false; | ||
``` | ||
|
||
--- | ||
|
||
问:如何解决 String 乱码 | ||
|
||
1. 选择可以表示中文的字符集 | ||
2. 在可以指定字符集的地方指定字符集 | ||
|
||
### Long | ||
|
||
- Long与Integer一样,都对一定范围内的值做了缓存,所以有些Long对象,数值相同的情况下,直接用==比较会相等 | ||
|
||
--- | ||
|
||
问:为什么使用 Long 时,大家推荐多使用 valueOf 方法,少使用 parseLong 方法 | ||
|
||
答:valueOf有做缓存 | ||
|
||
### 常用关键字 | ||
|
||
#### static | ||
|
||
- 修饰类变量 | ||
- 注意线程安全问题 | ||
- 修饰方法 | ||
- 方法可以通过类直接调用 | ||
- 修饰代码块 | ||
- 使用到静态变量的代码块可以在任何位置 | ||
|
||
**初始化时机** | ||
|
||
1. 父类的静态变量和静态块比子类优先初始化; | ||
2. 静态变量和静态块比类构造器优先初始化。 | ||
|
||
--- | ||
|
||
问:如何证明 static 静态变量和类实例无关 | ||
|
||
答:不需要创建该类的实例就可以使用静态变量与静态方法 | ||
|
||
问:变量和方法被 static 和 final 两个关键字修饰,为什么这么做 | ||
|
||
答:static可以直接使用这些方法与变量,final则是变量地址不可变,方法不可覆写,提升稳定性 | ||
|
||
问:atch 中发生了未知异常,finally 还会执行么 | ||
|
||
答:会,但是异常会被catch吞掉 | ||
|
||
#### final | ||
|
||
1. 被 final 修饰的类,表明该类是无法继承的; | ||
2. 被 final 修饰的方法,表明该方法是无法覆写的; | ||
3. 被 final 修饰的变量,说明该变量在声明的时候,就必须初始化完成,而且以后也不能修改其内存地址 | ||
|
||
第三点无法修改内存地址指的是无法修改引用,而不代表引用所指的对象内部无法修改 | ||
|
||
#### try、catch、finally | ||
|
||
代码的执行顺序为:try -> catch -> finally | ||
|
||
#### volatile | ||
|
||
常用来修饰某个共享变量,意思是当共享变量的值被修改后,会及时通知到其它线程上,其它线程就能知道当前共享变量的值已经被修改了 | ||
|
||
出现这种情况主要是因为JAVA的内存模型中的线程拥有一个工作区,线程对共享变量的读写都要先将变量从主存拉到工作区对其修改,修改后再将其写回到主存 | ||
|
||
![202002181601](/assets/202002181601.jfif) | ||
|
||
#### transient | ||
|
||
常用来修饰类变量,意思是当前变量是无需进行序列化的 | ||
|
||
#### default | ||
|
||
加在接口的方法上,修饰之后该方法就代表是一个默认实现,如果其他类继承该接口,就可以不用实现该方法,直接使用这个默认实现 | ||
|
||
|