Java 常用 API 详细笔记(含代码示例-熟记)

目录

1. API

1.1 API 概述

1.2 键盘录入字符串

2. String 类

2.1 String 概述

2.2 String 类的构造方法

2.3 创建字符串对象的区别对比

2.4 字符串的比较

2.5 String 方法小结

3. StringBuilder 类

3.1 StringBuilder 类概述

3.2 StringBuilder 类和 String 类的区别

3.3 StringBuilder 类的构造方法

3.4 StringBuilder 常用的成员方法

3.5 StringBuilder 和 String 相互转换

4. 常用 API

4.1 Math

4.2 System

4.3 Object 类的 toString 方法

4.4 Object 类的 equals 方法

4.5 Objects

4.6 BigDecimal

5. 包装类

5.1 基本类型包装类

5.2 Integer 类

5.3 自动拆箱和自动装箱

5.4 int 和 String 类型的相互转换

6. 时间日期类

6.1 Date 类

6.2 Date 类常用方法

6.3 SimpleDateFormat 类

7. JDK8 时间日期类

7.1 JDK8 新增日期类

7.2 LocalDateTime 创建方法

7.3 LocalDateTime 获取方法

7.4 LocalDateTime 转换方法

7.5 LocalDateTime 格式化和解析

7.6 LocalDateTime 增加或者减少时间的方法

7.7 LocalDateTime 修改方法

7.8 Period

7.9 Duration

 8. 其他常用 API

8.1 Arrays

8.2 ArrayList

1. ArrayList 的构造方法

2. ArrayList 的常用方法

2.1 添加元素

2.2 删除元素

2.3 修改元素

2.4 获取元素

2.5 获取集合大小

2.6 判断集合是否为空

2.7 判断是否包含元素

2.8 查找元素索引

2.9 清空集合

2.10 转换为数组

2.11 遍历集合

8.3 Collections

8.4 Files

8.5 IO 流

8.6 反射

8.7 其他常用 API

1. API

1.1 API 概述

  • API(Application Programming Interface):应用程序编程接口,是软件系统之间交互的桥梁。
  • Java 中的 API:JDK 提供的各种功能的 Java 类,封装了底层实现,开发者只需学习如何使用这些类。
  • 帮助文档:通过阅读 API 文档,了解类的方法、属性及其使用方式。

示例

// 查看 String 类的 API 文档
String str = "Hello";
System.out.println(str.length()); // 5

1.2 键盘录入字符串

  • Scanner 类
    • next():遇到空格或 Tab 键时停止录入。
    • nextLine():接收整行输入,直到回车换行符。

示例

Scanner scanner = new Scanner(System.in);
System.out.println("请输入字符串:");
String input = scanner.nextLine();
System.out.println("你输入的是:" + input);

2. String 类

2.1 String 概述

  • String 类:位于 java.lang 包下,代表字符串,Java 中所有双引号字符串都是 String 类的实例。
  • 字符串不可变:一旦创建,值不能被更改。

2.2 String 类的构造方法

  • 常用构造方法
    • String():创建一个空字符串。
    • String(String original):根据指定字符串创建新对象。

示例

String str1 = new String("Hello");
String str2 = "World";

2.3 创建字符串对象的区别对比

  • 通过构造方法创建:每次 new 都会申请新的内存空间,地址值不同。
  • 直接赋值方式创建:相同字符序列的字符串在字符串池中只维护一个对象。

示例

String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1 == s2); // false

String s3 = "abc";
String s4 = "abc";
System.out.println(s3 == s4); // true

2.4 字符串的比较

  • ==:比较引用数据类型的地址值。
  • equals():比较字符串内容。

示例

String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1.equals(s2)); // true

2.5 String 方法小结

  • 常用方法
    • equals():比较字符串内容,区分大小写。
    • equalsIgnoreCase():比较字符串内容,忽略大小写。
    • length():返回字符串长度。
    • charAt(int index):返回指定索引处的字符。
    • substring(int beginIndex, int endIndex):截取子字符串。

示例

String str = "Hello World";
System.out.println(str.substring(0, 5)); // Hello

3. StringBuilder 类

3.1 StringBuilder 类概述

  • StringBuilder:可变字符串类,内容可修改。

3.2 StringBuilder 类和 String 类的区别

  • String:不可变。
  • StringBuilder:可变。

3.3 StringBuilder 类的构造方法

  • 常用构造方法
    • StringBuilder():创建一个空的可变字符串对象。
    • StringBuilder(String str):根据指定字符串创建可变字符串对象。

示例

StringBuilder sb = new StringBuilder("Hello");

3.4 StringBuilder 常用的成员方法

  • 常用方法
    • append():添加数据并返回对象本身。
    • reverse():反转字符序列。

示例

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb.toString()); // Hello World

3.5 StringBuilder 和 String 相互转换

  • StringBuilder 转 StringtoString()
  • String 转 StringBuilderStringBuilder(String s)

示例

StringBuilder sb = new StringBuilder("Hello");
String str = sb.toString();
StringBuilder sb2 = new StringBuilder(str);

4. 常用 API

4.1 Math

  • Math 类:提供基本数学运算的静态方法。

示例

System.out.println(Math.abs(-10)); // 10
System.out.println(Math.ceil(10.1)); // 11.0

4.2 System

  • System 类:提供系统相关的方法。

示例

System.out.println(System.currentTimeMillis()); // 当前时间戳

4.3 Object 类的 toString 方法

  • toString():返回对象的字符串表示。

示例

class Person {
    String name;
    int age;
    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}
Person p = new Person();
System.out.println(p.toString());

4.4 Object 类的 equals 方法

  • equals():用于对象之间的比较。

示例

String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1.equals(s2)); // true

4.5 Objects

  • 常用方法
    • toString(Object obj):返回对象的字符串表示。
    • isNull(Object obj):判断对象是否为空。

示例

String str = null;
System.out.println(Objects.isNull(str)); // true

4.6 BigDecimal

  • BigDecimal:用于精确计算。

示例

BigDecimal bd1 = new BigDecimal("0.1");
BigDecimal bd2 = new BigDecimal("0.2");
System.out.println(bd1.add(bd2)); // 0.3

5. 包装类

5.1 基本类型包装类

  • 包装类:将基本数据类型封装成对象。

示例

Integer i = 10; // 自动装箱
int j = i; // 自动拆箱

5.2 Integer 类

  • Integer 类:包装 int 类型的值。

示例

Integer i = Integer.valueOf("10");

5.3 自动拆箱和自动装箱

  • 自动装箱:基本类型转换为包装类。
  • 自动拆箱:包装类转换为基本类型。

示例

Integer i = 10; // 自动装箱
int j = i; // 自动拆箱

5.4 int 和 String 类型的相互转换

  • int 转 String
int i = 10;
String s = i + "";
  • String 转 int
String s = "10";
int i = Integer.parseInt(s);

6. 时间日期类

6.1 Date 类

  • Date 类:代表特定时间,精确到毫秒。

示例

Date date = new Date();
System.out.println(date);

6.2 Date 类常用方法

  • 常用方法
    • getTime():返回自 1970 年 1 月 1 日以来的毫秒数。

示例

Date date = new Date();
System.out.println(date.getTime());

6.3 SimpleDateFormat 类

  • SimpleDateFormat:用于日期格式化和解析。

示例

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdf.format(new Date());
System.out.println(dateStr);

7. JDK8 时间日期类

7.1 JDK8 新增日期类

  • LocalDate:表示日期。
  • LocalTime:表示时间。
  • LocalDateTime:表示日期和时间。

7.2 LocalDateTime 创建方法

  • 常用方法
    • now():获取当前时间。
    • of():指定时间创建对象。

示例

LocalDateTime now = LocalDateTime.now();
LocalDateTime dateTime = LocalDateTime.of(2023, 10, 1, 12, 0);

7.3 LocalDateTime 获取方法

  • 常用方法
    • getYear():获取年份。
    • getMonthValue():获取月份。

示例

LocalDateTime now = LocalDateTime.now();
System.out.println(now.getYear());

7.4 LocalDateTime 转换方法

  • 常用方法
    • toLocalDate():转换为 LocalDate 对象。

示例

LocalDateTime now = LocalDateTime.now();
LocalDate date = now.toLocalDate();

7.5 LocalDateTime 格式化和解析

  • 常用方法
    • format():格式化日期。
    • parse():解析日期字符串。

示例

LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = now.format(formatter);
System.out.println(formatted);

7.6 LocalDateTime 增加或者减少时间的方法

  • 常用方法
    • plusYears():增加年份。
    • minusDays():减少天数。

示例

LocalDateTime now = LocalDateTime.now();
LocalDateTime nextYear = now.plusYears(1);

7.7 LocalDateTime 修改方法

  • 常用方法
    • withYear():修改年份。

示例

LocalDateTime now = LocalDateTime.now();
LocalDateTime newDateTime = now.withYear(2024);

7.8 Period

  • Period:计算两个日期之间的间隔。

示例

LocalDate start = LocalDate.of(2023, 1, 1);
LocalDate end = LocalDate.of(2023, 10, 1);
Period period = Period.between(start, end);
System.out.println(period.getMonths()); // 9

7.9 Duration

  • Duration:计算两个时间之间的间隔。

示例

LocalTime start = LocalTime.of(10, 0);
LocalTime end = LocalTime.of(12, 0);
Duration duration = Duration.between(start, end);
System.out.println(duration.toHours()); // 2

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()
    .filter(n -> n % 2 == 0)
    .collect(Collectors.toList());
System.out.println(evenNumbers); // [2, 4]

int sum = numbers.stream().reduce(0, Integer::sum);
System.out.println(sum); // 15

 8. 其他常用 API

8.1 Arrays

  • Arrays 类:提供操作数组的静态方法。
    • sort():对数组进行排序。
    • toString():将数组转换为字符串。
    • binarySearch():对排序后的数组进行二分查找。
    • copyOf():复制数组。
    • fill():用指定值填充数组。

示例

int[] arr = {3, 1, 2};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // [1, 2, 3]

int index = Arrays.binarySearch(arr, 2);
System.out.println(index); // 1

int[] copyArr = Arrays.copyOf(arr, arr.length);
System.out.println(Arrays.toString(copyArr)); // [1, 2, 3]

Arrays.fill(arr, 0);
System.out.println(Arrays.toString(arr)); // [0, 0, 0]

8.2 ArrayList

  • ArrayList:位于 java.util 包中,是一个可动态调整大小的数组。
  • 特点
    • 有序:元素按照插入顺序存储。
    • 可重复:允许存储重复元素。
    • 非线程安全:在多线程环境下需要手动同步。

1. ArrayList 的构造方法
  • 常用构造方法
    • ArrayList():创建一个空的 ArrayList。
    • ArrayList(Collection<? extends E> c):创建一个包含指定集合元素的 ArrayList。

示例

ArrayList<String> list1 = new ArrayList<>();
ArrayList<String> list2 = new ArrayList<>(Arrays.asList("A", "B", "C"));

2. ArrayList 的常用方法
2.1 添加元素
  • add(E e):在列表末尾添加元素。
  • add(int index, E element):在指定索引处插入元素。

示例

ArrayList<String> list = new ArrayList<>();
list.add("A"); // [A]
list.add(1, "B"); // [A, B]
2.2 删除元素
  • remove(Object o):删除指定元素(首次出现)。
  • remove(int index):删除指定索引处的元素。

示例

ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
list.remove("B"); // [A, C]
list.remove(0); // [C]
2.3 修改元素
  • set(int index, E element):修改指定索引处的元素。

示例

ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
list.set(1, "X"); // [A, X, C]
2.4 获取元素
  • get(int index):获取指定索引处的元素。

示例

ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
String element = list.get(1); // B
2.5 获取集合大小
  • size():返回集合中元素的个数。

示例

ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
int size = list.size(); // 3
2.6 判断集合是否为空
  • isEmpty():判断集合是否为空。

示例

ArrayList<String> list = new ArrayList<>();
boolean isEmpty = list.isEmpty(); // true
2.7 判断是否包含元素
  • contains(Object o):判断集合是否包含指定元素。

示例

ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
boolean contains = list.contains("B"); // true
2.8 查找元素索引
  • indexOf(Object o):返回指定元素首次出现的索引。
  • lastIndexOf(Object o):返回指定元素最后一次出现的索引。

示例

ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "B"));
int firstIndex = list.indexOf("B"); // 1
int lastIndex = list.lastIndexOf("B"); // 3
2.9 清空集合
  • clear():清空集合中的所有元素。

示例

ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
list.clear(); // []
2.10 转换为数组
  • toArray():将集合转换为数组。

示例

ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
Object[] array = list.toArray();
for (Object o : array) {
    System.out.println(o); // A, B, C
}
2.11 遍历集合
  • 普通 for 循环
ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
}
  • 增强 for 循环
for (String s : list) {
    System.out.println(s);
}
  • 迭代器
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

8.3 Collections

  • Collections 类:提供操作集合的静态方法。
    • sort():对列表进行排序。
    • reverse():反转列表中的元素。
    • shuffle():随机打乱列表中的元素。
    • max():返回列表中的最大值。
    • min():返回列表中的最小值。
    • binarySearch():对排序后的列表进行二分查找。

示例

List<Integer> list = new ArrayList<>(Arrays.asList(3, 1, 2));
Collections.sort(list);
System.out.println(list); // [1, 2, 3]

Collections.reverse(list);
System.out.println(list); // [3, 2, 1]

Collections.shuffle(list);
System.out.println(list); // 随机顺序

int max = Collections.max(list);
int min = Collections.min(list);
System.out.println("Max: " + max + ", Min: " + min);

int index = Collections.binarySearch(list, 2);
System.out.println(index); // 查找元素 2 的索引

8.4 Files

  • Files 类:提供操作文件的静态方法。
    • write():将数据写入文件。
    • readAllLines():读取文件的所有行。
    • copy():复制文件。
    • delete():删除文件。
    • exists():判断文件是否存在。

示例

Path path = Paths.get("test.txt");
Files.write(path, "Hello World".getBytes());

List<String> lines = Files.readAllLines(path);
System.out.println(lines); // [Hello World]

Path copyPath = Paths.get("test_copy.txt");
Files.copy(path, copyPath);

Files.deleteIfExists(copyPath);

boolean exists = Files.exists(path);
System.out.println("File exists: " + exists);

8.5 IO 流

  • IO 流:用于处理输入输出的类。
    • 字节流
      • FileInputStream:读取文件字节流。
      • FileOutputStream:写入文件字节流。
    • 字符流
      • FileReader:读取文件字符流。
      • FileWriter:写入文件字符流。
    • 缓冲流
      • BufferedReader:缓冲读取字符流。
      • BufferedWriter:缓冲写入字符流。

示例

// 字节流
try (FileInputStream fis = new FileInputStream("test.txt");
     FileOutputStream fos = new FileOutputStream("test_copy.txt")) {
    int data;
    while ((data = fis.read()) != -1) {
        fos.write(data);
    }
} catch (IOException e) {
    e.printStackTrace();
}

// 字符流
try (FileReader fr = new FileReader("test.txt");
     FileWriter fw = new FileWriter("test_copy.txt")) {
    int data;
    while ((data = fr.read()) != -1) {
        fw.write(data);
    }
} catch (IOException e) {
    e.printStackTrace();
}

// 缓冲流
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"));
     BufferedWriter bw = new BufferedWriter(new FileWriter("test_copy.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        bw.write(line);
        bw.newLine();
    }
} catch (IOException e) {
    e.printStackTrace();
}

8.6 反射

  • 反射:在运行时动态获取类的信息并操作类的属性和方法。
    • Class 类:获取类的信息。
    • Field 类:获取类的字段。
    • Method 类:获取类的方法。
    • Constructor 类:获取类的构造方法。

示例

class Person {
    private String name;
    public int age;

    public Person() {}

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void sayHello() {
        System.out.println("Hello, " + name);
    }
}

// 获取 Class 对象
Class<?> clazz = Class.forName("Person");

// 获取构造方法并创建对象
Constructor<?> constructor = clazz.getConstructor(String.class, int.class);
Object person = constructor.newInstance("Alice", 25);

// 获取字段并修改值
Field ageField = clazz.getField("age");
ageField.set(person, 30);

// 获取方法并调用
Method sayHelloMethod = clazz.getMethod("sayHello");
sayHelloMethod.invoke(person);

8.7 其他常用 API

  • Stream API:用于处理集合和数组的流式操作。
    • filter():过滤元素。
    • map():转换元素。
    • reduce():聚合元素。
    • collect():将流转换为集合。

示例

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()
    .filter(n -> n % 2 == 0)
    .collect(Collectors.toList());
System.out.println(evenNumbers); // [2, 4]

int sum = numbers.stream().reduce(0, Integer::sum);
System.out.println(sum); // 15

以上内容涵盖了 Java 中常用的 API、集合、IO 流、反射等知识点,每个部分都附带了示例代码,便于理解和实践。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值