一、集合框架(Collections)
文字解析:
Java集合主要分为Collection(单列)和Map(双列)两大接口族。
List:有序、可重复。ArrayList基于动态数组,随机访问快,增删慢;LinkedList基于双向链表,增删快,随机访问慢。Set:无序、不可重复。HashSet基于哈希表,O(1)访问;TreeSet基于红黑树,可排序。Map:键值对。HashMap允许一个null键和多个null值,非线程安全;ConcurrentHashMap采用分段锁/CAS,线程安全且高并发。
代码示例:
java
// List List<String> arrayList = new ArrayList<>(); arrayList.add("Java"); arrayList.add("Python"); System.out.println(arrayList.get(0)); // Java // Set Set<Integer> hashSet = new HashSet<>(); hashSet.add(10); hashSet.add(20); hashSet.add(10); // 重复元素不会被添加 System.out.println(hashSet.size()); // 2 // Map Map<String, Integer> hashMap = new HashMap<>(); hashMap.put("A", 1); hashMap.put("B", 2); hashMap.put(null, 0); // 允许null键 System.out.println(hashMap.get("A")); // 1 // 遍历Map for (Map.Entry<String, Integer> entry : hashMap.entrySet()) { System.out.println(entry.getKey() + "=" + entry.getValue()); }二、并发编程(Concurrency)
文字解析:
线程创建:继承
Thread或实现Runnable、Callable(有返回值)。同步机制:
synchronized(内置锁)和ReentrantLock(显式锁)。synchronized自动释放锁,ReentrantLock需手动unlock(),但支持尝试锁、公平锁等高级功能。线程池:推荐使用
ExecutorService,避免手动创建线程。Executors提供工厂方法,但FixedThreadPool和CachedThreadPool队列过长易OOM,实际生产多用ThreadPoolExecutor自定义参数。原子类:
AtomicInteger等通过CAS保证线程安全,无锁高效。
代码示例:
java
// 1. 实现Runnable class MyTask implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + " running"); } } // 2. synchronized 同步方法 public synchronized void syncMethod() { /* 临界区 */ } // 3. ReentrantLock 示例 ReentrantLock lock = new ReentrantLock(); lock.lock(); try { // 临界区 } finally { lock.unlock(); } // 4. 自定义线程池 ThreadPoolExecutor executor = new ThreadPoolExecutor( 2, 4, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100), new ThreadPoolExecutor.CallerRunsPolicy() ); executor.execute(() -> System.out.println("Task executed")); // 5. AtomicInteger AtomicInteger ai = new AtomicInteger(0); ai.incrementAndGet(); // 原子+1 System.out.println(ai.get()); // 1 executor.shutdown();三、JVM内存模型与垃圾回收
文字解析:
运行时数据区:堆(所有对象实例)、栈(局部变量、方法调用)、方法区(类信息、常量、静态变量)、程序计数器(线程私有)、本地方法栈。
垃圾回收:判断存活——引用计数法(循环引用问题)和可达性分析法(GC Roots)。
GC算法:标记-清除(有碎片)、标记-复制(新生代,无碎片)、标记-整理(老年代,无碎片)。
常用收集器:G1(分代+区域化,可预测停顿)、ZGC(超低延迟,TB级堆)。
类加载机制:加载→验证→准备→解析→初始化;双亲委派模型(BootStrap→Extension→Application→自定义),保证核心类安全性。
代码示例(演示内存与GC):
java
// 可通过 -Xms10m -Xmx10m 运行观察GC public class JvmDemo { public static void main(String[] args) { List<byte[]> list = new ArrayList<>(); for (int i = 0; i < 100; i++) { // 不断创建大对象,触发GC byte[] arr = new byte[1024 * 1024]; // 1MB list.add(arr); } System.out.println("Done"); } }四、IO与NIO
文字解析:
BIO(Blocking IO):面向流,同步阻塞,每个连接一个线程,适合连接数少且固定的场景。
NIO(Non-blocking IO):面向缓冲区(Buffer)、通道(Channel)、选择器(Selector),支持多路复用,一个线程可管理多个连接。
AIO(Asynchronous IO):基于事件和回调,异步非阻塞,但实际应用较少。
代码示例(NIO读取文件):
java
try (FileChannel channel = FileChannel.open(Paths.get("data.txt"), StandardOpenOption.READ)) { ByteBuffer buffer = ByteBuffer.allocate(1024); while (channel.read(buffer) != -1) { buffer.flip(); // 切换为读模式 while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); } buffer.clear(); // 清空缓冲区 } } catch (IOException e) { e.printStackTrace(); }五、Java 8+ 新特性
文字解析:
Lambda表达式:简化匿名内部类,实现函数式接口(如
Runnable、Comparator)。Stream API:支持链式操作(
filter、map、reduce)对集合进行声明式处理,支持并行流。Optional:优雅解决空指针异常。
新的日期时间API:
LocalDate、LocalTime、LocalDateTime,线程安全且不可变。
代码示例:
java
// Lambda + Stream List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int sum = numbers.stream() .filter(n -> n % 2 == 0) // 过滤偶数 .mapToInt(n -> n * n) // 求平方 .sum(); // 求和 System.out.println(sum); // 4+16=20 // Optional 使用 Optional<String> opt = Optional.ofNullable(null); String result = opt.orElse("默认值"); System.out.println(result); // 默认值 // 新日期API LocalDate today = LocalDate.now(); LocalDate future = today.plusDays(7); System.out.println("7天后: " + future);六、异常处理
文字解析:
检查型异常(Checked):继承
Exception,必须try-catch或throws,如IOException。非检查型异常(Unchecked):继承
RuntimeException,不强制处理,如NullPointerException。最佳实践:捕获具体异常而非
Exception;使用finally释放资源(或try-with-resources)。
代码示例:
java
// try-with-resources 自动关闭资源 try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { String line = br.readLine(); System.out.println(line); } catch (IOException e) { System.err.println("读取文件失败: " + e.getMessage()); }七、反射与注解
文字解析:
反射:运行时获取类、方法、字段信息,用于框架(Spring)和动态代理。
注解:元数据,分为源码级(
@Override)、编译时(Lombok)、运行时(Spring@Autowired)。可通过反射读取运行时注解。
代码示例(反射):
java
// 通过反射调用方法 Class<?> clazz = Class.forName("java.util.ArrayList"); Object list = clazz.getDeclaredConstructor().newInstance(); Method addMethod = clazz.getMethod("add", Object.class); addMethod.invoke(list, "Reflection"); System.out.println(list); // [Reflection]