Reborn's Blog

Java基础知识1

2018-11-10·Java, Collection, Serialization

Java 基本类型

| 基本类型 | 类成员初始值 | | --- | --- | | boolean | false | | char | '�' (null) | | byte | (byte)0 | | short | (short)0 | | int | 0 | | long | 0L | | float | 0.0f | | double | 0.0d |

注意:定义在函数中的局部变量会被随机初始化。

for each 语句

char[] s = {'a', 'b', 'c'};
for (char ele : s) {
    System.out.println(ele);
}

数组拷贝

// 完整拷贝
int[] copied = Arrays.copyOf(original, original.length);

// 不规则数组
int[][] odds = new int[NMAX + 1][];
for (int n = 0; n <= NMAX; n++) {
    odds[n] = new int[n + 1];
}

CopyOnWriteArrayList

读写分离,写操作在复制的数组上进行(需要加锁),读操作在原始数组上(不需加锁)。写成功后把原始数组指向新的复制数组。

LinkedHashMap 与 LRU 缓存

继承自 HashMap,内部维护双向链表,维护插入顺序或 LRU 顺序。

class LRUCache<K, V> extends LinkedHashMap<K, V> {
    private static final int MAX_ENTRIES = 3;

    protected boolean removeEldestEntry(Map.Entry eldest) {
        return size() > MAX_ENTRIES;
    }

    LRUCache() {
        super(MAX_ENTRIES, 0.75f, true);
    }
}

transient 关键字

  • 只能修饰变量,不能修饰类和方法
  • 类必须实现 Serializable 接口
  • transient 变量不能被序列化
  • 静态变量无论是否 transient 修饰均不能被序列化
#Java#Collection#Serialization