当前位置: 首页 > web >正文

Java常用类

一、字符串处理类

1. String 类

  • 特点:不可变性(每次操作生成新对象)。

  • 常用方法

String str = "Hello, Java!";// 获取长度
int len = str.length();        // 12// 拼接字符串
String newStr = str.concat("!!");  // "Hello, Java!!!"// 截取子串
String sub = str.substring(7);     // "Java!"// 分割字符串
String[] parts = str.split(",");   // ["Hello", " Java!"]// 替换字符
String replaced = str.replace('a', 'o'); // "Hello, Jovo!"// 转换为字符数组
char[] chars = str.toCharArray();
  • 注意:频繁修改字符串应使用StringBuilderStringBuffer

2. StringBuilder & StringBuffer

  • 可变字符串:适用于高频修改场景。

  • 区别

    • StringBuilder:非线程安全,性能高(推荐使用)。

    • StringBuffer:线程安全,性能略低。

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");      // "Hello World"
sb.insert(5, ",");        // "Hello, World"
sb.delete(5, 7);          // "Hello World"
sb.reverse();             // "dlroW olleH"

二、集合框架类

1. ArrayList

  • 动态数组:基于数组实现,支持快速随机访问。

  • 常用操作

ArrayList<String> list = new ArrayList<>();list.add("Apple");         // 添加元素
list.add(0, "Banana");     // 在索引0插入
list.remove("Apple");      // 删除元素
String item = list.get(0); // 获取元素
int size = list.size();    // 获取大小
boolean isEmpty = list.isEmpty(); // 判断空
  • 注意:删除元素时建议使用迭代器避免并发问题。

2. HashMap

  • 键值对存储:基于哈希表,允许null键和值。

  • 常用方法

HashMap<String, Integer> map = new HashMap<>();map.put("Alice", 25);      // 添加键值对
int age = map.get("Alice"); // 获取值 → 25
map.remove("Alice");        // 删除键
boolean hasKey = map.containsKey("Bob"); // 检查键
Set<String> keys = map.keySet();         // 获取所有键
  • 注意:键对象必须正确重写hashCode()equals()方法。

三、包装类(Wrapper Classes)

  • 用途:将基本类型转换为对象(如intInteger)。

  • 自动装箱/拆箱

Integer num = 10;      // 自动装箱(int → Integer)
int value = num;       // 自动拆箱(Integer → int)

常用方法

String str = "123";
int num = Integer.parseInt(str);   // 字符串转int → 123
String binary = Integer.toBinaryString(10); // 10 → "1010"

四、日期时间类

1. LocalDateLocalTimeLocalDateTime(Java 8+)

  • 推荐替代DateCalendar:更直观且线程安全。

LocalDate date = LocalDate.now();          // 当前日期
LocalTime time = LocalTime.of(14, 30);     // 14:30
LocalDateTime dateTime = LocalDateTime.parse("2023-10-05T08:30:00");// 日期计算
LocalDate nextWeek = date.plusWeeks(1);    // 加1周

2. DateTimeFormatter

  • 格式化日期

LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = now.format(formatter);  // "2023-10-05 14:30:00"

五、工具类

1. Math

  • 数学运算

double sqrt = Math.sqrt(25);      // 5.0
double pow = Math.pow(2, 3);      // 8.0
int max = Math.max(10, 20);       // 20
double random = Math.random();    // 0.0 ≤ random < 1.0

2. System

  • 系统级操作

long time = System.currentTimeMillis();  // 当前时间戳
System.out.println("输出内容");          // 控制台打印
System.arraycopy(src, 0, dest, 0, len); // 数组复制
3. Scanner
  • 读取输入

Scanner scanner = new Scanner(System.in);
System.out.print("请输入姓名:");
String name = scanner.nextLine();    // 读取整行
int age = scanner.nextInt();         // 读取整数
scanner.close();

六、文件操作类(File

  • 文件/目录管理

File file = new File("test.txt");boolean exists = file.exists();      // 文件是否存在
boolean created = file.createNewFile(); // 创建新文件
boolean deleted = file.delete();     // 删除文件
long size = file.length();           // 文件大小(字节)

七、异常处理类

  • 常见异常类型

    • NullPointerException:空指针异常

    • ArrayIndexOutOfBoundsException:数组越界

    • IOException:输入输出异常

try {int[] arr = new int[5];arr[10] = 50;  // 抛出ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {System.out.println("数组越界:" + e.getMessage());
} finally {System.out.println("无论是否异常都会执行");
}

八、最佳实践与常见问题

1、字符串比较:使用equals()而非==

String s1 = new String("Java");
String s2 = "Java";
System.out.println(s1.equals(s2));  // true(值相等)
System.out.println(s1 == s2);       // false(对象地址不同)

2、集合初始化:优先使用泛型指定类型。

ArrayList<Integer> numbers = new ArrayList<>();  // 避免强制类型转换

3、日期处理:避免使用过时的DateCalendar,改用Java 8+的时间API。

http://www.xdnf.cn/news/4041.html

相关文章:

  • 51单片机入门教程——蜂鸣器播放天空之城
  • centos8源码安装openssl
  • Ubuntu安装编译环境
  • 使用 NGINX 实现 HTTP Basic 认证ngx_http_auth_basic_module 模块
  • Dify - Embedding Rerank
  • React状态管理
  • Java面试场景分析:从音视频到安全与风控的技术探讨
  • 怎么才能找到自己的天赋?
  • 09-24计算机考研408真题及答案
  • uniapp开发05-image标签的一些使用注意事项
  • GPIO引脚的上拉下拉以及转换速度到底怎么选
  • 使用注意力机制的seq2seq
  • Docker —— 隔离的基本操作(2)
  • ABAP 导入Excel形成内表
  • spring中的@ConfigurationProperties注解详解
  • 网星安全AWS攻防方案,重磅发布!
  • 机器学习模型训练模块技术文档
  • AVHRR中国积雪物候数据集(1980-2020年)
  • yolo 用roboflow标注的数据集本地训练 kaggle训练 comet使用 训练笔记5
  • FISCO BCOS【初体验笔记】
  • Python 闭包:函数式编程中的魔法变量容器
  • ciscn_2019_c_1
  • 普联的AC100+AP+易展路由组网方案的一些问题
  • docker介绍以及安装
  • sherpa-ncnn:Linux_x86交叉编译Linux_arm32上的sherpa-ncnn -- 语音转文本大模型
  • 蓝桥杯单片机备战笔记
  • 【中间件】brpc_基础_TimerThread
  • 五一假期作业
  • springboot单体项目的执行流程
  • LFU算法解析