Java学习第五部分——API部分

发布于:2025-07-03 ⋅ 阅读:(24) ⋅ 点赞:(0)

目录

一、字符串处理

1. String类

(1)不可变性

(2)常用方法

2. StringBuilder和StringBuffer类

(1)可变性

(2)线程安全

(3)常用方法

二、集合框架

1. List接口

   - ArrayList

   - LinkedList

2. Set接口

   - HashSet

   - TreeSet

3. Map接口

   - HashMap

   - TreeMap

三、IO流

1. 文件输入输出

   - FileInputStream和FileOutputStream

   - FileReader和FileWriter

2. 缓冲流

   - BufferedInputStream和BufferedOutputStream

   - BufferedReader和BufferedWriter

四.idea项目实战——字符串处理

五.idea项目实战——集合框架

六.idea项目实战——IO流


ps:Java API(Java Application Programming Interface)是Java语言的核心库,它为开发者提供了一系列预定义的类和接口,用于实现各种功能。这些类和接口涵盖了从基础数据结构到高级功能的各个方面。

一、字符串处理


1. String类


(1)不可变性

       `String`对象一旦创建,其内容就不能被修改。每次对字符串进行操作(如拼接、截取等)时,都会生成一个新的`String`对象。


(2)常用方法


     - **拼接字符串**:可以使用`+`操作符,也可以使用`concat()`方法。例如:

       String str1 = "Hello";
       String str2 = "World";
       String result1 = str1 + " " + str2; // 使用+操作符
       String result2 = str1.concat(" ").concat(str2); // 使用concat()方法

     - **获取字符串长度**:使用`length()`方法。例如:

       String str = "Hello";
       int length = str.length(); // length的值为5

     - **字符串比较**:使用`equals()`方法比较字符串内容是否相同,使用`==`比较字符串引用是否相同。例如:

       String str1 = "Hello";
       String str2 = "Hello";
       String str3 = new String("Hello");
       boolean isEqual1 = str1.equals(str2); // true
       boolean isEqual2 = str1 == str2; // true
       boolean isEqual3 = str1 == str3; // false

     - **字符串查找**:使用`indexOf()`方法查找子字符串的位置。例如:
    
       String str = "HelloWorld";
       int index = str.indexOf("World"); // index的值为5

     - **字符串转换**:可以使用`toUpperCase()`、`toLowerCase()`等方法将字符串转换为大写或小写。例如:

       String str = "Hello";
       String upperStr = str.toUpperCase(); // upperStr的值为"HELLO"
       String lowerStr = str.toLowerCase(); // lowerStr的值为"hello"
 

2. StringBuilder和StringBuffer类

(1)可变性

       `StringBuilder`和`StringBuffer`都是可变的字符串类,可以对字符串进行修改操作。
   

(2)线程安全

       `StringBuffer`是线程安全的,而`StringBuilder`不是线程安全的。在单线程环境下,推荐使用`StringBuilder`,因为它性能更高。


(3)常用方法


     - **字符串拼接**:使用`append()`方法。例如:
      
       StringBuilder sb = new StringBuilder();
       sb.append("Hello").append(" ").append("World");
       String result = sb.toString(); // result的值为"Hello World"
    
     - **字符串插入**:
使用`insert()`方法。例如:

       StringBuilder sb = new StringBuilder("HelloWorld");
       sb.insert(5, " "); // 在索引5的位置插入空格
       String result = sb.toString(); // result的值为"Hello World"

     - **字符串删除**:使用`delete()`方法。例如:
   
       StringBuilder sb = new StringBuilder("Hello World");
       sb.delete(5, 6); // 删除索引5到6(不包括6)之间的字符
       String result = sb.toString(); // result的值为"HelloWorld"
  

二、集合框架


1. List接口


   - ArrayList


     - **基于动态数组实现**:适合随机访问,可以通过索引快速获取元素。
     - **线程不安全**:在多线程环境下,需要手动同步。
     - **常用方法**:
       - **添加元素**:使用`add()`方法。例如:
    
         List<String> list = new ArrayList<>();
         list.add("Apple");
         list.add("Banana");

       - **获取元素**:使用`get()`方法。例如:
 
         String element = list.get(0); // element的值为"Apple"

       - **删除元素**:使用`remove()`方法。例如:

         list.remove(0); // 删除索引为0的元素
 


   - LinkedList


     - **基于双向链表实现**:适合频繁的插入和删除操作。
     - **线程不安全**:在多线程环境下,需要手动同步。
     - **常用方法**
       - **添加元素**:使用`add()`方法。例如:
     
         List<String> list = new LinkedList<>();
         list.add("Apple");
         list.add("Banana");
 
       - **获取元素**:使用`get()`方法。例如:
   
         String element = list.get(0); // element的值为"Apple"
       
       - **删除元素**:使用`remove()`方法。例如:
       
         list.remove(0); // 删除索引为0的元素
     

2. Set接口


   - HashSet


     - **基于哈希表实现**:不允许重复元素,元素的添加顺序和遍历顺序可能不同。
     - **线程不安全**:在多线程环境下,需要手动同步。
     - **常用方法**
       - **添加元素**:使用`add()`方法。例如:

         Set<String> set = new HashSet<>();
         set.add("Apple");
         set.add("Banana");

       - **检查元素是否存在**:使用`contains()`方法。例如:
     
         boolean contains = set.contains("Apple"); // contains的值为true
   
       - **删除元素**:使用`remove()`方法。例如:
     
         set.remove("Apple"); // 删除元素"Apple"
   


   - TreeSet


     - **基于红黑树实现**:不允许重复元素,元素会按照自然顺序或指定的比较器顺序进行排序。
     - **线程不安全**:在多线程环境下,需要手动同步。
     - **常用方法**
       - **添加元素**:使用`add()`方法。例如:
        
         Set<String> set = new TreeSet<>();
         set.add("Apple");
         set.add("Banana");

       - **获取第一个元素**:使用`first()`方法。例如:

         String firstElement = set.first(); // firstElement的值为"Apple"

       - **获取最后一个元素**:使用`last()`方法。例如:
 
         String lastElement = set.last(); // lastElement的值为"Banana"
 

3. Map接口


   - HashMap


     - **基于哈希表实现**:存储键值对,键不允许重复,值可以重复。
     - **线程不安全**:在多线程环境下,需要手动同步。
     - **常用方法**
       - **添加键值对**:使用`put()`方法。例如:
         
         Map<String, Integer> map = new HashMap<>();
         map.put("Apple", 10);
         map.put("Banana", 20);
 
       - **获取值**:使用`get()`方法。例如:
     
         Integer value = map.get("Apple"); // value的值为10
      
       - **删除键值对**:使用`remove()`方法。例如:
   
         map.remove("Apple"); // 删除键为"Apple"的键值对
  


   - TreeMap


     - **基于红黑树实现**:存储键值对,键不允许重复,键会按照自然顺序或指定的比较器顺序进行排序。
     - **线程不安全**:在多线程环境下,需要手动同步。
     - **常用方法**
       - **添加键值对**:使用`put()`方法。例如:
 
         Map<String, Integer> map = new TreeMap<>();
         map.put("Apple", 10);
         map.put("Banana", 20);

       - **获取第一个键值对**:使用`firstEntry()`方法。例如:
    
         Map.Entry<String, Integer> firstEntry = map.firstEntry(); // firstEntry的键为"Apple",值为10

       - **获取最后一个键值对**:使用`lastEntry()`方法。例如:

         Map.Entry<String, Integer> lastEntry = map.lastEntry(); // lastEntry的键为"Banana",值为20
 

三、IO流


1. 文件输入输出


   - FileInputStream和FileOutputStream


     - **文件输入流**:`FileInputStream`用于从文件中读取数据。例如:

       try (FileInputStream fis = new FileInputStream("input.txt"))
       {
           byte[] buffer = new byte[1024];
           int length;
           while ((length = fis.read(buffer)) != -1)
           {
               // 处理读取到的数据
           }
       }
       catch (IOException e)
       {
           e.printStackTrace();
       }

     - **文件输出流**:`FileOutputStream`用于向文件写入数据。例如:

       try (FileOutputStream fos = new FileOutputStream("output.txt"))
       {
           String data = "Hello, World!";
           fos.write(data.getBytes());
       }
       catch (IOException e)
       {
           e.printStackTrace();
       }
 


   - FileReader和FileWriter


     - **文件字符输入流**:`FileReader`用于从文件中读取字符数据。例如:

       try (FileReader fr = new FileReader("input.txt"))
       {
           char[] buffer = new char[1024];
           int length;
           while ((length = fr.read(buffer)) != -1)
           {
               // 处理读取到的字符数据
           }
       }
       catch (IOException e)
       {
           e.printStackTrace();
       }

     - **文件字符输出流**:`FileWriter`用于向文件写入字符数据。例如:

       try (FileWriter fw = new FileWriter("output.txt"))
       {
           String data = "Hello, World!";
           fw.write(data);
       }
       catch (IOException e)
       {
           e.printStackTrace();
       }
 

2. 缓冲流


   - BufferedInputStream和BufferedOutputStream


     - **缓冲输入流**:`BufferedInputStream`用于提高文件读取效率。例如:

       try (FileInputStream fis = new FileInputStream("input.txt");
            BufferedInputStream bis = new BufferedInputStream(fis))
       {
           byte[] buffer = new byte[1024];
           int length;
           while ((length = bis.read(buffer)) != -1)
           {
               // 处理读取到的数据
           }
       }
       catch (IOException e)
       {
           e.printStackTrace();
       }

     - **缓冲输出流**:`BufferedOutputStream`用于提高文件写入效率。例如:

       try (FileOutputStream fos = new FileOutputStream("output.txt");
            BufferedOutputStream bos = new BufferedOutputStream(fos))
       {
           String data = "Hello, World!";
           bos.write(data.getBytes());
       }
       catch (IOException e)
       {
           e.printStackTrace();
       }
 


   - BufferedReader和BufferedWriter

BufferedReader

缓冲字符输入流BufferedReader用于提高字符文件读取效率。例如:

try (FileReader fr = new FileReader("input.txt");
     BufferedReader br = new BufferedReader(fr))
{
    String line;
    while ((line = br.readLine()) != null)
    {
        // 处理读取到的每一行数据
        System.out.println(line); // 打印每一行数据
    }
}
catch (IOException e)
{
    e.printStackTrace(); // 打印异常信息
}

BufferedWriter

缓冲字符输出流BufferedWriter用于提高字符文件写入效率。例如:

try (FileWriter fw = new FileWriter("output.txt");
     BufferedWriter bw = new BufferedWriter(fw))
{
    bw.write("Hello, World!"); // 写入一行数据
    bw.newLine(); // 写入一个换行符
    bw.write("This is a test."); // 写入另一行数据
}
catch (IOException e)
{
    e.printStackTrace(); // 打印异常信息
}

四.idea项目实战——字符串处理

示例代码如下(将下列代码直接复制粘贴Main,java文件中即可编译运行)

public class Main {
    public static void main(String[] args) {
        // 使用String进行字符串拼接
        String name = "Alice";
        String greeting = "Hello, " + name + "!"; // 使用+操作符
        System.out.println(greeting);

        // 使用StringBuilder进行字符串拼接
        StringBuilder sb = new StringBuilder();
        sb.append("Hello, ").append(name).append("!");
        String greeting2 = sb.toString();
        System.out.println(greeting2);

        // 字符串转换为大写
        String upperCaseGreeting = greeting.toUpperCase();
        System.out.println("Uppercase greeting: " + upperCaseGreeting);

        // 字符串查找
        int index = greeting.indexOf("Alice");
        System.out.println("Index of 'Alice': " + index);

        // 使用StringBuffer进行线程安全的字符串拼接
        StringBuffer sb2 = new StringBuffer();
        sb2.append("Hello, ").append(name).append("!");
        String greeting3 = sb2.toString();
        System.out.println(greeting3);

        // 演示字符串的不可变性
        String originalString = "Hello";
        String modifiedString = originalString.concat(" World");
        System.out.println("Original string: " + originalString); // 不变
        System.out.println("Modified string: " + modifiedString); // 新字符串

        // 演示StringBuilder的可变性
        StringBuilder sb3 = new StringBuilder("Hello");
        sb3.append(" World");
        System.out.println("StringBuilder after modification: " + sb3.toString()); // 修改后的字符串
    }
}

输出结果如下

代码解释如下

  1. 使用String进行字符串拼接

    • 使用+操作符将字符串拼接起来。

    • greeting变量存储了拼接后的字符串。

  2. 使用StringBuilder进行字符串拼接

    • StringBuilder是一个可变的字符串类,适合在单线程环境下进行字符串拼接操作。

    • 使用append()方法将字符串拼接起来。

  3. 字符串转换为大写

         使用toUpperCase()方法将字符串转换为大写。

  4. 字符串查找

         使用indexOf()方法查找子字符串的位置。

  5. 使用StringBuffer进行线程安全的字符串拼接

    • StringBuffer是一个线程安全的可变字符串类,适合在多线程环境下使用。

    • 使用append()方法将字符串拼接起来。

  6. 演示字符串的不可变性

         String对象一旦创建,其内容就不能被修改。concat()方法会返回一个新的字符串。

  7. 演示StringBuilder的可变性

         StringBuilder对象的内容可以被修改。append()方法会直接修改StringBuilder对象的内容。

五.idea项目实战——集合框架

示例代码如下

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // 使用List存储和操作有序集合
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        System.out.println("Fruits List: " + fruits);

        // 使用Set存储和操作无序集合,不允许重复
        Set<String> uniqueFruits = new HashSet<>(fruits);
        System.out.println("Unique Fruits Set: " + uniqueFruits);

        // 使用TreeSet对元素进行排序
        Set<String> sortedFruits = new TreeSet<>(fruits);
        System.out.println("Sorted Fruits Set: " + sortedFruits);

        // 使用Map存储键值对
        Map<String, Integer> fruitCounts = new HashMap<>();
        fruitCounts.put("Apple", 3);
        fruitCounts.put("Banana", 5);
        fruitCounts.put("Cherry", 2);

        System.out.println("Fruit Counts Map: " + fruitCounts);

        // 使用TreeMap对键进行排序
        Map<String, Integer> sortedFruitCounts = new TreeMap<>(fruitCounts);
        System.out.println("Sorted Fruit Counts Map: " + sortedFruitCounts);

        // 演示List的索引访问
        String firstFruit = fruits.get(0);
        System.out.println("First fruit in the list: " + firstFruit);

        // 演示Set的元素检查
        boolean containsBanana = uniqueFruits.contains("Banana");
        System.out.println("Does the set contain 'Banana'? " + containsBanana);

        // 演示Map的键值对访问
        int appleCount = fruitCounts.get("Apple");
        System.out.println("Count of 'Apple': " + appleCount);

        // 演示遍历List
        System.out.println("Iterating over List:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }

        // 演示遍历Set
        System.out.println("Iterating over Set:");
        for (String fruit : uniqueFruits) {
            System.out.println(fruit);
        }

        // 演示遍历Map
        System.out.println("Iterating over Map:");
        for (Map.Entry<String, Integer> entry : fruitCounts.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

输出结果如下

代码解释如下

  1. 使用String进行字符串拼接

    • 使用+操作符将字符串拼接起来。

    • greeting变量存储了拼接后的字符串。

  2. 使用StringBuilder进行字符串拼接

    • StringBuilder是一个可变的字符串类,适合在单线程环境下进行字符串拼接操作。

    • 使用append()方法将字符串拼接起来。

  3. 字符串转换为大写

         使用toUpperCase()方法将字符串转换为大写。
  4. 字符串查找

         使用indexOf()方法查找子字符串的位置。
  5. 使用StringBuffer进行线程安全的字符串拼接

    • StringBuffer是一个线程安全的可变字符串类,适合在多线程环境下使用。

    • 使用append()方法将字符串拼接起来。

  6. 演示字符串的不可变性

         String对象一旦创建,其内容就不能被修改。concat()方法会返回一个新的字符串。
  7. 演示StringBuilder的可变性

         StringBuilder对象的内容可以被修改。append()方法会直接修改StringBuilder对象的内容。
  8. 使用List存储和操作有序集合

    • ArrayList是一个基于动态数组的实现,适合随机访问。

    • 使用add()方法添加元素,使用get()方法通过索引访问元素。

  9. 使用Set存储和操作无序集合,不允许重复

    • HashSet是一个基于哈希表的实现,不允许重复元素。

    • 使用add()方法添加元素,使用contains()方法检查元素是否存在。

  10. 使用TreeSet对元素进行排序

    • TreeSet是一个基于红黑树的实现,可以对元素进行自然排序或指定排序。

    • 使用add()方法添加元素,元素会自动排序。

  11. 使用Map存储键值对

    • HashMap是一个基于哈希表的实现,存储键值对,键不允许重复。

    • 使用put()方法添加键值对,使用get()方法通过键获取值。

  12. 使用TreeMap对键进行排序

    • TreeMap是一个基于红黑树的实现,可以对键进行自然排序或指定排序。

    • 使用put()方法添加键值对,键会自动排序。

  13. 演示List的索引访问

         使用get()方法通过索引访问List中的元素。
  14. 演示Set的元素检查

         使用contains()方法检查Set中是否存在某个元素。
  15. 演示Map的键值对访问

         使用get()方法通过键获取Map中的值。
  16. 演示遍历ListSetMap

    • 使用增强型for循环遍历ListSet

    • 使用entrySet()方法遍历Map的键值对。

六.idea项目实战——IO流

示例代码与“input.txt”文件和“output.txt”文件内容如下,演示如何使用BufferedReaderBufferedWriter来读取和写入文件

import java.io.*;

public class Main {
    public static void main(String[] args) {
        String inputFilePath = "input.txt";
        String outputFilePath = "output.txt";

        // 使用BufferedReader读取文件
        try (BufferedReader br = new BufferedReader(new FileReader(inputFilePath));
             BufferedWriter bw = new BufferedWriter(new FileWriter(outputFilePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 处理每一行数据,例如转换为大写
                String processedLine = line.toUpperCase();
                // 将处理后的数据写入到输出文件
                bw.write(processedLine);
                bw.newLine(); // 写入换行符
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("File processing complete.");
    }
}

输出结果如下

代码解释如下

  1. 文件路径

    • inputFilePath:输入文件的绝对路径,这里假设文件位于C:\daimai目录下,文件名为input.txt

    • outputFilePath:输出文件的绝对路径,这里假设文件位于C:\daimai目录下,文件名为output.txt

  2. 路径分隔符

         在Java中,路径分隔符\是一个转义字符,因此需要使用双反斜杠\\来表示一个普通的反斜杠。例如,C:\\daimai\\input.txt
  3. 异常处理

    • 使用try-catch块捕获和处理可能发生的IOException,避免程序因异常而中断。

    • 如果文件不存在,捕获FileNotFoundException并打印错误信息。

  4. 资源管理

         使用try-with-resources语句自动关闭资源,确保文件流在操作完成后被正确关闭,避免资源泄露。


网站公告

今日签到

点亮在社区的每一天
去签到