Appearance
Java 常用 API 笔记
1. 集合框架(Collection Framework)
List:有序集合,允许重复元素
ArrayList
:基于数组实现,默认容量为10,动态增长LinkedList
:基于链表实现,插入和删除效率高
Map:键值对存储结构
HashMap
:常用,不保证顺序;默认负载因子0.75TreeMap
:按自然顺序排序
java
import java.util.ArrayList;
import java.util.HashMap;
public class CollectionExample {
public static void main(String[] args) {
// ArrayList 示例
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println(list.get(0)); // 输出 Apple
// HashMap 示例
HashMap<Integer, String> map = new HashMap<>();
map.put(123, "John");
System.out.println(map.get(123)); // 输出 John
}
}
2. IO 流(InputStream 和 OutputStream)
- FileInputStream:读取文件内容
- OutputStream:写入数据到文件
java
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class IOStreamExample {
public static void main(String[] args) throws Exception {
String filePath = "src/test.txt";
// 从文件读取数据
FileInputStream fis = new FileInputStream(filePath);
byte[] bytes = new byte[1024];
int readBytes = fis.read(bytes);
System.out.println(new String(bytes, 0, readBytes));
// 写入数据到文件
FileOutputStream fos = new FileOutputStream(filePath + ".copy");
String dataToWrite = "Hello World";
fos.write(dataToWrite.getBytes());
}
}
3. 异常处理(Exception Handling)
- try-catch-finally:用于捕捉和处理异常
- 自定义异常:继承 Exception 或 RuntimeException
java
public class ExceptionExample {
public static void main(String[] args) {
try {
// 可能抛出异常的代码
int division = 10 / 0;
} catch (ArithmeticException e) { // 捕捉具体异常类型
System.out.println("除以零错误:" + e.getMessage());
} finally {
System.out.println("这总会执行");
}
}
public static void main(String[] args) throws MyCustomException {
throw new MyCustomException("自定义异常示例");
}
}
class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
4. 多线程(Thread)
- Runnable:实现 Runnable 接口
- Thread:继承 Thread 类
java
public class MultiThreadingExample implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("线程 " + Thread.currentThread().getName() + ": 计数 " + i);
try {
Thread.sleep(100); // 线程休眠
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MultiThreadingExample task = new MultiThreadingExample();
// 创建线程并启动
Thread thread1 = new Thread(task, "Thread-1");
Thread thread2 = new Thread(task, "Thread-2");
thread1.start();
thread2.start();
}
}
5. 反射(Reflection)
- Class:获取类信息
java
import java.lang.reflect.Field;
public class ReflectionExample {
public static void main(String[] args) throws Exception {
Class<Person> personClass = Person.class;
// 获取所有字段
Field[] fields = personClass.getDeclaredFields();
for (Field field : fields) {
System.out.println("字段名:" + field.getName());
System.out.println("修饰符:" + Modifier.toString(field.getModifiers()));
}
}
}
class Person {
private String name;
public int age;
}
6. 数据库连接(JDBC)
- DriverManager:获取数据库连接
java
import java.sql.Connection;
import java.sql.DriverManager;
public class JDBCExample {
public static void main(String[] args) throws Exception {
// 加载驱动
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "password";
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("连接成功!");
}
}
7. 网络编程(Socket)
- ServerSocket:创建服务器端套接字
- Socket:客户端连接
java
import java.net.ServerSocket;
import java.net.Socket;
public class NetworkExample {
public static void main(String[] args) throws Exception {
// 服务端
ServerSocket server = new ServerSocket(1234);
System.out.println("服务器已启动,等待连接...");
Socket client = server.accept();
System.out.println("客户端已连接");
client.close();
}
}
8. hashCode与equals的关系
hashCode的作用
在Java中,每个对象都可以通过调用hashCode
方法获取其哈希值。哈希值可以看作是对象的“指纹信息”,用于快速区分不同对象。equals的作用
equals
方法通常用于比较两个对象的值是否相等。在Object
类中,默认的equals
方法比较的是两个对象的内存地址(即引用是否相同)。集合中的比较逻辑
在Java的一些集合类(如HashMap
、HashSet
)中,判断两个对象是否相等时,通常会先比较它们的hashCode
值:
- 如果
hashCode
不同,则认为两个对象不相等。 - 如果
hashCode
相同,则进一步调用equals
方法进行详细比较。
- 重写注意事项
当重写equals
方法时,必须同时重写hashCode
方法,以确保两者逻辑一致。否则可能导致集合类无法正确识别对象,从而引发错误。
总结
以上是Java开发中常用的API知识点和示例代码。这些内容涵盖了集合框架、IO流、异常处理、多线程等核心主题,适合初学或复习使用。