Files
mkdocs/docs/android面试/基础知识/Java基础.md

544 lines
9.9 KiB
Markdown
Raw Normal View History

2026-01-15 11:53:37 +08:00
# Java基础
## 目录
- [面向对象编程](#面向对象编程)
- [集合框架](#集合框架)
- [异常处理](#异常处理)
- [泛型](#泛型)
- [反射](#反射)
- [注解](#注解)
- [多线程基础](#多线程基础)
- [IO流](#io流)
- [JVM基础](#jvm基础)
- [面试常见问题](#面试常见问题)
---
## 面向对象编程
### 三大特性
#### 1. 封装
```java
// 封装:隐藏内部实现,提供公共接口
public class User {
private String name; // 私有属性
private int age;
// 公共方法访问私有属性
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
```
#### 2. 继承
```java
// 继承:子类继承父类的属性和方法
public class Animal {
protected String name;
public void eat() {
System.out.println("Animal is eating");
}
}
public class Dog extends Animal {
public void bark() {
System.out.println("Dog is barking");
}
@Override
public void eat() {
System.out.println("Dog is eating");
}
}
```
#### 3. 多态
```java
// 多态:同一接口,不同实现
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animal1.eat(); // 调用 Dog 的 eat 方法
animal2.eat(); // 调用 Cat 的 eat 方法
```
### 抽象类和接口
```java
// 抽象类:可以有抽象方法和具体方法
public abstract class Animal {
public abstract void makeSound();
public void sleep() {
System.out.println("Animal is sleeping");
}
}
// 接口只有抽象方法Java 8+ 可以有默认方法)
public interface Flyable {
void fly();
default void land() {
System.out.println("Landing");
}
}
```
---
## 集合框架
### List
```java
// ArrayList动态数组
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.get(0); // "A"
// LinkedList双向链表
List<String> linkedList = new LinkedList<>();
linkedList.add("A");
linkedList.addFirst("B");
```
### Set
```java
// HashSet无序不重复
Set<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("A"); // 重复,不会添加
// TreeSet有序不重复
Set<String> treeSet = new TreeSet<>();
treeSet.add("C");
treeSet.add("A");
treeSet.add("B");
// 输出A, B, C
```
### Map
```java
// HashMap键值对无序
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.get("A"); // 1
// TreeMap键值对有序
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("C", 3);
treeMap.put("A", 1);
treeMap.put("B", 2);
// 按键排序A, B, C
```
### 集合遍历
```java
// for-each 循环
for (String item : list) {
System.out.println(item);
}
// Iterator
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
System.out.println(item);
}
// Stream APIJava 8+
list.stream()
.filter(s -> s.startsWith("A"))
.forEach(System.out::println);
```
---
## 异常处理
### 异常类型
```java
// Throwable
// ├── Error错误不可恢复
// └── Exception异常可恢复
// ├── RuntimeException运行时异常
// └── CheckedException检查异常
// RuntimeException不需要捕获
int[] arr = new int[5];
int value = arr[10]; // ArrayIndexOutOfBoundsException
// CheckedException必须捕获或声明
try {
FileInputStream fis = new FileInputStream("file.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
```
### 异常处理
```java
// try-catch-finally
try {
// 可能抛出异常的代码
int result = 10 / 0;
} catch (ArithmeticException e) {
// 处理异常
System.out.println("除零错误");
} catch (Exception e) {
// 处理其他异常
e.printStackTrace();
} finally {
// 无论是否异常都会执行
System.out.println("清理资源");
}
// try-with-resourcesJava 7+
try (FileInputStream fis = new FileInputStream("file.txt")) {
// 使用资源
} catch (IOException e) {
e.printStackTrace();
} // 自动关闭资源
```
### 自定义异常
```java
// 自定义异常
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// 使用
public void method() throws CustomException {
throw new CustomException("自定义异常");
}
```
---
## 泛型
### 泛型类
```java
// 泛型类
public class Box<T> {
private T item;
public void setItem(T item) {
this.item = item;
}
public T getItem() {
return item;
}
}
// 使用
Box<String> stringBox = new Box<>();
stringBox.setItem("Hello");
String value = stringBox.getItem();
```
### 泛型方法
```java
// 泛型方法
public <T> T getValue(T value) {
return value;
}
// 使用
String str = getValue("Hello");
Integer num = getValue(123);
```
### 通配符
```java
// 上界通配符:? extends T
List<? extends Number> list1; // 可以是 Number 及其子类
// 下界通配符:? super T
List<? super Integer> list2; // 可以是 Integer 及其父类
// 无界通配符:?
List<?> list3; // 可以是任何类型
```
---
## 反射
### 获取 Class 对象
```java
// 方式1通过类名
Class<?> clazz = String.class;
// 方式2通过对象
String str = "Hello";
Class<?> clazz2 = str.getClass();
// 方式3通过类名字符串
Class<?> clazz3 = Class.forName("java.lang.String");
```
### 反射操作
```java
// 创建对象
Class<?> clazz = User.class;
User user = (User) clazz.newInstance();
// 获取字段
Field field = clazz.getDeclaredField("name");
field.setAccessible(true);
field.set(user, "John");
// 获取方法
Method method = clazz.getMethod("getName");
String name = (String) method.invoke(user);
// 获取构造函数
Constructor<?> constructor = clazz.getConstructor(String.class);
User user2 = (User) constructor.newInstance("John");
```
---
## 注解
### 内置注解
```java
// @Override:重写方法
@Override
public void method() { }
// @Deprecated:已废弃
@Deprecated
public void oldMethod() { }
// @SuppressWarnings:抑制警告
@SuppressWarnings("unchecked")
public void method() { }
```
### 自定义注解
```java
// 定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value() default "";
int count() default 0;
}
// 使用注解
@MyAnnotation(value = "test", count = 5)
public void method() { }
// 读取注解
Method method = MyClass.class.getMethod("method");
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
String value = annotation.value();
```
---
## 多线程基础
### 创建线程
```java
// 方式1继承 Thread
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running");
}
}
MyThread thread = new MyThread();
thread.start();
// 方式2实现 Runnable
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread running");
}
}
Thread thread2 = new Thread(new MyRunnable());
thread2.start();
// 方式3Lambda 表达式
Thread thread3 = new Thread(() -> {
System.out.println("Thread running");
});
thread3.start();
```
### 线程同步
```java
// synchronized 关键字
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
// Lock
private Lock lock = new ReentrantLock();
public void method() {
lock.lock();
try {
// 临界区代码
} finally {
lock.unlock();
}
}
```
---
## IO流
### 字节流
```java
// FileInputStream / FileOutputStream
try (FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt")) {
int data;
while ((data = fis.read()) != -1) {
fos.write(data);
}
}
```
### 字符流
```java
// FileReader / FileWriter
try (FileReader fr = new FileReader("input.txt");
FileWriter fw = new FileWriter("output.txt")) {
int data;
while ((data = fr.read()) != -1) {
fw.write(data);
}
}
```
### 缓冲流
```java
// BufferedInputStream / BufferedOutputStream
try (BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("input.txt"));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("output.txt"))) {
int data;
while ((data = bis.read()) != -1) {
bos.write(data);
}
}
```
---
## JVM基础
### 内存区域
```java
// JVM 内存区域
// 1. 程序计数器:当前执行指令的地址
// 2. 虚拟机栈:方法执行时的栈帧
// 3. 本地方法栈Native 方法执行
// 4. 堆:对象实例
// 5. 方法区:类信息、常量、静态变量
```
### 垃圾回收
```java
// GC 算法
// 1. 标记-清除
// 2. 标记-复制
// 3. 标记-整理
// 4. 分代收集
// GC 类型
// - Minor GC新生代回收
// - Major GC老年代回收
// - Full GC整个堆回收
```
---
## 面试常见问题
### Q1: Java 三大特性?
**答案:**
1. **封装**:隐藏内部实现,提供公共接口
2. **继承**:子类继承父类的属性和方法
3. **多态**:同一接口,不同实现
### Q2: ArrayList 和 LinkedList 的区别?
**答案:**
- **ArrayList**:基于数组,随机访问快,插入删除慢
- **LinkedList**:基于链表,随机访问慢,插入删除快
### Q3: HashMap 的实现原理?
**答案:**
- 基于数组和链表Java 8+ 使用红黑树)
- 通过 hashCode 计算数组索引
- 解决冲突使用链表或红黑树
### Q4: 异常处理的机制?
**答案:**
- **try-catch-finally**:捕获和处理异常
- **throws**:声明可能抛出的异常
- **throw**:抛出异常
### Q5: 泛型的作用?
**答案:**
1. 类型安全:编译时检查类型
2. 消除强制转换
3. 提高代码可读性
---
*最后更新2024年*