核心
参考
- https://blog.csdn.net/weixin_49307485/article/details/120881646
- https://cloud.tencent.com/developer/article/1642713
- https://blog.csdn.net/u012834750/article/details/79361552
https://zhuanlan.zhihu.com/p/29715594
java.lang
系统基础
Object
equals
- 对于双等号==来说,比较的是值是否相等如果双等号比较的是基本数据类型的变量,则直接比较变量的值是否相等,如果双等号比较的是引用类型的变量,则比较的是所指向对象的地址。
- 对于equals来说,比较的是是否是同一个对象如果没有对equals方法进行重写,则直接比较引用类型的变量指向的对象所在的地址如果有String、Data等类对equals进行了重写了,则比较的是所指向对象的内容。
- hashCode 不是java实现的
- // TODO hash 算法专题
-
Class
参考
ClassLoader
- 参考
重点
参考
Boolean 的hashcode 为何这样实现 return value ? 1231 : 1237;
- equals 实现
- 通过valueOf 返回的对象 早已分配好内存 ```java public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
public static Boolean valueOf(String s) { return parseBoolean(s) ? TRUE : FALSE; }
- parseBoolean
- getBoolean // 和系统属性有关
- 实现了Comparable 接口,所以 compareTo, 静态方法 compare
- 逻辑运算
- logicalAnd
- logicalOr
- logicalXor
<a name="NbEFA"></a>
#### Charactor
- valueOf, 注意部分会用到缓存,
```java
static final Character cache[] = new Character[127 + 1];
static {
for (int i = 0; i < cache.length; i++)
cache[i] = new Character((char)i);
}
//.....
if (c <= 127) { // must cache
return CharacterCache.cache[(int)c];
}
return new Character(c);
- hashCode, equals,toString
- isValidCodePoint
- isBmpCodePoint
- isSupplementaryCodePoint
- isHighSurrogate
- isLowSurrogate
- isSurrogate
- isSurrogatePair
- charCount
- toCodePoint
- codePointAt
- codePointAtImpl
- codePointBefore
- highSurrogate
- lowSurrogate
- toChars
- codePointCount
- offsetByCodePoints
- isLowerCase
- isUpperCase
- isTitleCase
- isDigit
- isDefined
- isLetter
- isLetterOrDigit
- isAlphabetic
- isIdeographic
- isJavaIdentifierStart
- isJavaIdentifierPart
- isUnicodeIdentifierStart
- isUnicodeIdentifierPart
- isIdentifierIgnorable
- toLowerCase
- toUpperCase
- toTitleCase
- digit
- getNumericValue
- isSpaceChar
- isWhitespace // 空白符包含:空格、tab键、换行符
- isISOControl ??
- getType
- forDigit
- getDirectionality ??
- isMirrored //类似各种括号,需要一对一对的
- compareTo
- compare
- reverseBytes
- getName
Number
-
Byte ,
Byte用 ByteCache做了缓存 所以用valueOf 返回的同值的都是同一个地址对象
static final Byte cache[] = new Byte[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Byte((byte)(i - 128));
}
parseByte 从String 转Byte
- 实现 Number定义的方法,实现都是强转,不会有精度丢失
- 实现了Comparable 接口
toUnsignedInt 与 toUnsignedLong
Short,
表示范围 从 ~
valueOf 同样用了缓存
if (sAsInt >= -128 && sAsInt <= 127) { // must cache
return ShortCache.cache[sAsInt + offset];
}
return new Short(s);
decode 转0x 0X 这样开头的字符串
- 实现 Number定义的方法,实现都是强转,
- 实现了Comparable 接口
- reverseBytes 静态方法
toUnsignedInt, toUnsignedLong 实现都是位运算
Integer,
构造方法支持 int String
- toXXXString 转各种进制的String
- parseInt parseUnsignedInt 静态方法,String转int
- vlaueOf 支持String ,int 有缓存实现,缓存大小可以配置 ```java if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i);
//……… static final int low = -128; static final int high; static final Integer cache[];
static { // high value may be configured by property int h = 127; String integerCacheHighPropValue = sun.misc.VM.getSavedProperty(“java.lang.Integer.IntegerCache.high”); if (integerCacheHighPropValue != null) { try { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low) -1); } catch( NumberFormatException nfe) { // If the property cannot be parsed into an int, ignore it. } } high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
- 实现 Number接口,都是强转
- getInteger,获取系统变量值 System.getProperty(nm);
- decode
- 实现Compareble接口
- divideUnsigned 应该是除
- remainderUnsigned 求余
- highestOneBit 与lowestOneBit [参考](https://blog.csdn.net/cnds123321/article/details/117399430)
- numberOfLeadingZeros与numberOfTrailingZeros 二进制串中从最左/右边算起连续的“0”的总数量
- bitCount 在二进制下“1”的数量。//位运算 TODO
- rotateLeft 与rotateRight // 补码相关
- reverse
- signum 判断正负数
- reverseBytes
- 比较 求和 max min sum 用Math函数实现
<a name="ODPop"></a>
#### Long,
- 类型转换 toXXXString, parseXXXLong
- valueOf 也可转String到Long,有缓存 -128~127
- 实现 Number接口,都是强转
- getLong 和系统变量有关
- Compareble接口实现
- 后面和Integer类似
<a name="SZGzK"></a>
#### Float
- 与Integer 有区别的
- isNaN 实现有点奇怪 return (v != v);
- NaN是一个Float对象;
- NaN对象的内存地址尽不相同
- isInfinite
- hashCode 与 equals
- floatToIntBits floatToRawIntBits //非java代码
<a name="bAKBv"></a>
#### Double
- 与Float基本类似
<a name="Z8fHh"></a>
### 字符处理
<a name="SkYcb"></a>
#### String
- final class
- 构造函数 byte[] int[] char[] StringBuffer , 一般有偏移量和 个数
- codePoint相关
- getChars getBytes
- CharSequence 的方法实现
- valueOf 相关 copyValueOf 实现看上去都是一样的
- format相关
- 各种equals
- contentEquals 支持CharSequence StringBuffer
- nonSyncContentEquals
- equalsIgnoreCase
- Comparable接口实现
- regionMatches , 一个区间内的子字符串是否相等
- startWith endWith
- hashCode h = 31 * h + val[i];
- xxxIndexOfxxx 检索 match contians 匹配
- subxxx 子串
- replacexxx
- concat split join trim,split是在Pattern类中实现,join与split是相反的过程
- 大小写转
<a name="V2qQ8"></a>
#### String Builder
- 有个初始容量 容量可设置
```java
public StringBuffer() {
super(16);
}
public StringBuffer(int capacity) {
super(capacity);
}
public StringBuffer(String str) {
super(str.length() + 16);
append(str);
}
最多常用的是append 有15个左右重载,主要逻辑如下, 在父类中实现
public AbstractStringBuilder append(String str) {
if (str == null)
return appendNull();
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
- insert方法 类似方法都用System.arraycopy 和String getChars,都是数组操作
public AbstractStringBuilder insert(int offset, String str) {
if ((offset < 0) || (offset > length()))
throw new StringIndexOutOfBoundsException(offset);
if (str == null)
str = "null";
int len = str.length();
ensureCapacityInternal(count + len);
System.arraycopy(value, offset, value, offset + len, count - offset);
str.getChars(value, offset);
count += len;
return this;
}
运行相关
Thead //TODO 在多线程专题
Process
//略System
输入输出相关
public final static InputStream in = null;
public final static PrintStream out = null;
public final static PrintStream err = null;
- setIn setOut setErr
- console
- Channel inheritedChannel
- getSecurityManager / setSecurityManager
- 时间相关
- nanoTime
- currentTimeMillis
- 内存操作
- arraycopy //非java实现
- gc
- runFinalization
- 环境相关
- xxxProperties
- xxxenv
- 库加载 实现是RumTime类里实现
- load
- loadLibray
- mapLibraryName
RunTime
- exec // ProcessBuilder 调用 UNIXProcess 的方法实现
- xxxShutDownHook
- halt
- 运行资源信息
- availableProcessors
- freeMemory
- totalMemory
- maxMemory
- 加载lib方法
- 内存回收
- gc
- runFinalization
追踪开关
java.lang.management
参考
https://blog.csdn.net/weixin_33716154/article/details/92275908
java.lang.ref
参考
https://www.iteye.com/blog/seanzhou-2021773 | 引用类型 | 取得目标对象的方式 | 垃圾回收条件 | 是否可能内在泄漏 | | —- | —- | —- | —- | | 强引用 | 直接引用 | 不回收 | 可能 | | 软引用 | 通过get()方法 | 无强引用时,视内存情况及get()调用情况回收 | 不可能 | | 弱引用 | 通过get()方法 | 无强引用时,永远回收 | 不可能 | | 虚引用 (跟踪回收用) | 无法取得 | 无强引用时,永远回收 | 不可能 |
java.lang.reflect
参考
https://blog.csdn.net/muddledape/article/details/81091174
java.util
参考
https://blog.csdn.net/weixin_46482482/article/details/115731362
容器接口
Collection
接口 ,子接口有 Set,List,Queue
- 通用的方法
- add addAll
- remove removeAll removeIf clear
- contains containsAll retainAll
- size isEmpty
- toArray
- Steam //TODO
- stream parallelStream
-
List
新增实现的方法 接口中实现方法 用 default
- sort
- repalceAll
新增的接口方法
相较Collection没有新增方法,不能按索引获取值
-
Queue
侧重操作
size , isEmpty containsKey containsValue
- keySet entrySet //??
- put putAll putIfAbsent
- remove clear
- replaceAll replace merge
- get values getOrDefaut
- computeIfAbsent computeIfPresent compute //??
-
模板类
AbstractXXX
-
常用实现类
ArrayList
构造函数
- 数组实现,初始容量为10,可以指定容量
- 实现Collection接口的可以转
实现技巧
实现 了 ist
, Deque , 等接口 - 是个双向链表
- 构造函数
- 可以直接把实现了Collection接口的类转过来
- getFirst getLast addFirst addlast removeFirst removeLast
- add addAll
- clear remove
- get set
- indexOf lastIndexOf
- Deque的方法实现
- offer offerFirst offerLast
- peek peekFirst peekLast element
- poll pollFist polllast remove
- push pop
- removeFirstOccurrence removeLastOccurrence
- descendingIterator
-
Vector
与ArrayList最大的区别应该就是线程安全的
扩容有点不一样,默认arrayList是1.5倍 vector是2倍
Stack
继承Vector
- push pop peek
-
HashSet
构造函数
- 底层是HashMap,初始化时可以设置一些hashmap初始化的参数,来提升性能
- 看一个默认的初始化 集合实例, 应该是用0.75的负载因子比较合适 ```java public HashSet(Collection<? extends E> c) { map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16)); addAll(c); }
- set 较List 少一些查找的方法
<a name="WCpRm"></a>
#### TreeSet
- 实现了 NavigableSet 与 SortedSet 接口,主要是有序的特性
- 构造函数
- 可以用 NavigableMap接口实现的类来初始化
- 默认用TreeMap 来存,
- 也可以转其他Collection的实例
- descendingIterator
- descendingSet
- subSet headSet 返回比参数小的 集合 tailSet 返回比参数大的集合
- comparator
- first last lower floor ceiling higher
- pollFirt pollLast
<a name="J8IxS"></a>
#### HashMap
- 重要实现
- TREEIFY_THRESHOLD 是 8 ,每个“筒” 下面超过这个,就变成了TreeNode
```java
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
- get containsKey getOrDefault values keySet entrySet
- size isEmpty
- put putAll putIfAbsent remove clear
computeIfAbsent computIfPresent compute
HashTable
参考
- https://zhuanlan.zhihu.com/p/165264462
- 基本被淘汰
TreeMap
红黑树 //TODO
- 有序
核心代码 ```java public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
private void fixAfterInsertion(Entry
while (x != null && x != root && x.parent.color == RED) {
if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
Entry<K,V> y = rightOf(parentOf(parentOf(x)));
if (colorOf(y) == RED) {
setColor(parentOf(x), BLACK);
setColor(y, BLACK);
setColor(parentOf(parentOf(x)), RED);
x = parentOf(parentOf(x));
} else {
if (x == rightOf(parentOf(x))) {
x = parentOf(x);
rotateLeft(x);
}
setColor(parentOf(x), BLACK);
setColor(parentOf(parentOf(x)), RED);
rotateRight(parentOf(parentOf(x)));
}
} else {
Entry<K,V> y = leftOf(parentOf(parentOf(x)));
if (colorOf(y) == RED) {
setColor(parentOf(x), BLACK);
setColor(y, BLACK);
setColor(parentOf(parentOf(x)), RED);
x = parentOf(parentOf(x));
} else {
if (x == leftOf(parentOf(x))) {
x = parentOf(x);
rotateRight(x);
}
setColor(parentOf(x), BLACK);
setColor(parentOf(parentOf(x)), RED);
rotateLeft(parentOf(parentOf(x)));
}
}
}
root.color = BLACK;
}
<a name="ywPUR"></a>
### 常用工具类
<a name="IgqF4"></a>
#### Arrays
- sort
- 底层DualPivotQuicksort ,ComparableTimSort这里实现 //TODO
- [https://zhuanlan.zhihu.com/p/374041792](https://zhuanlan.zhihu.com/p/374041792)
- parallelSort
- parallelPrefix
- binarySearch
- equals
- fill
- copyOf copyOfRange
- asList
- hascode
- deepHashCode
- deepEquals
- toString
- deepToString
- parallelSetAll setAll //TODO lambada
- [https://www.cnblogs.com/sweetorangezzz/p/12918962.html](https://www.cnblogs.com/sweetorangezzz/p/12918962.html)
- spliterator
- [https://blog.csdn.net/sl1992/article/details/100149187](https://blog.csdn.net/sl1992/article/details/100149187)
- stream //TODO
- 参考 [https://blog.csdn.net/a13662080711/article/details/84928181](https://blog.csdn.net/a13662080711/article/details/84928181)
<a name="YFV0S"></a>
## java.util.concurrent
<a name="dZ5FY"></a>
### 参考
- [https://www.cnblogs.com/sarafill/archive/2011/05/18/2049461.html](https://www.cnblogs.com/sarafill/archive/2011/05/18/2049461.html)
- [https://blog.csdn.net/qq_27378875/article/details/81610696](https://blog.csdn.net/qq_27378875/article/details/81610696)
<a name="ZMYdd"></a>
### 线程安全容器接口及其实现
- BlockingDeque, BlockingQueue
- ConcurrentMap,ConcurrentNavigableMap
<a name="M9aNk"></a>
## java.util.concurrent.atomic
<a name="NKPIQ"></a>
#### Atomicxxxx
- 有 AtomicBoolean,AtomicInteger,AtomicIntegerArray,AtomicReference等
- [volatile关键字了解下](https://www.cnblogs.com/dolphin0520/p/3920373.html)
- 使用了 [Unsafe](https://www.jianshu.com/p/db8dce09232d) 主要使用了CAS 能力
- [atomicStampReference](https://blog.csdn.net/zxl1148377834/article/details/90079882)
- [其它类](https://blog.csdn.net/panweiwei1994/article/details/78739264)
<a name="Ej4Fs"></a>
## java.util.concurrent.locks
<a name="ODJDP"></a>
### 参考
- [https://www.cnblogs.com/Jason-Xiang/p/8446554.html](https://www.cnblogs.com/Jason-Xiang/p/8446554.html)
- <br />
<a name="KdUM4"></a>
#### AbstractQueuedSynchronizer
- 参考
- [https://blog.csdn.net/qq_39241239/article/details/86934059](https://blog.csdn.net/qq_39241239/article/details/86934059)
<a name="us0Lk"></a>
#### Lock
<a name="mAe4g"></a>
#### Condition
- 参考
- [https://blog.csdn.net/a1439775520/article/details/98471610](https://blog.csdn.net/a1439775520/article/details/98471610)
<a name="piSwY"></a>
#### ReentrantLock
- 内部类 主要实现了锁的逻辑
- Sync
- NonfairSync
- FairSync
```java
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
构造函数
public ReentrantLock() {
sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
- 默认不公平锁
- Lock 接口实现
- lock
- 主要通过 Sync及子类NonfairSync FairSync实现 lock,代码在AbstractQueuedSynchronizer里实现
- lockInterruptibly
- tryLock
- unLock
- newCondition
- lock