常用类
一、包装类
概念:包装类是将基本数据类型封装到一个类中, 包含属性和方法,方便对象操作。
包装类位于java.lang包中。
二、包装类和基本数据类型
- 基本数据类型转换为包装类
Integer inValue = new Integer(22);
或Integer inValue = new Integer("22");
Integer inValue = Integer.valueOf("22");
- 包装类转换为基本类型
Integer integerld = new Integer(22);
int intld = integerld.inValue();
- 基本数据类型和包装类的自动转换
Integer intObject = 5;
int intValue = intObject;
注意:包装类并不是用来取代基本类型的。
自动装箱和自动拆箱
- 自动装箱
1、基本类型就自动地封装到与它相同类型的包装中,如:
Integer i = 100;
2、本质上,编译器编译时为我们添加了:Integer i = Integer.valueOf(100);
- 自动拆箱
1、包装类对象自动转换成基本类型数据。如:
int a = new Integet(100);
2、本质上,编译器编译时为我们添加了:int a = new Integer(100).intValue();
三、字符串相关类
- 生活中的字符串
- 使用String对象存储字符串
String s = "Hello World";
String s = new String();
String s = new String("Hello World");
- String类位于java.lang包中,具有丰富的方法。
-
- 计算字符串长度、比较字符串、连接字符串、提取字符串
字符串的本质:
- 计算字符串长度、比较字符串、连接字符串、提取字符串
1、字符串的本质是字符数组或者叫做字符序列。
2、String类使用final修饰,不可以被继承。
3、String是一个不可变对象。
String(不可变字符序列)
Java字符串就是Unicode字符序列,例如字符串"Java"就是4个Unicode字符J,a,v,a组成的。
- Java允许使用字符"+"把两个字符串连接起来
String s1 = "Hello";
String s2 = "World!";
String s = s1 + s2;// HelloWorld!
String类的常用方法
// 返回字符串中第index个字符。
char charAt(int index)
// 如果字符串与other相等,返回true
boolean equals(String other)
// 如果字符串与other相等(忽略大小写),则返回true
boolean equalslgnoreCase(String other)
// 返回 String 对象内第一次出现子字符串的字符位置
int indexOf(String str)
// 用于返回字符串中最后一次出现指定子字符串的位置索引。如果未找到指定子字符串,则返回 -1。该方法从字符串的末尾开始搜索
LastIndexOf(String str, int idx)
// 返回字符串的长度
int length()
// 返回一个新串,它是通过用newChar替换此字符串中出现的所有oldChar而生成的
String replace(char oldChar, char newChar)
// 如果字符串以prefix开始,则返回true
boolean startsWith(String prefix)
// 如果字符串以prefix结尾,则返回true
boolean endsWith(String prefix)
// 返回一个新字符串,该串包含从原始字符串beginIndex到串尾或endIndex-1的所有字符串
String substring(int beginIndex)
String substring(int beginIndex, int endIndex)
// 返回一个新字符串,该串将原始字符串中的所有大写字母改成小写字母
String toLowerCase()
// 返回一个新字符串,该串将原始字符串中的所有小写字母改成大写字母
String toUpperCase()
// 返回一个新字符串,该串删除了原始字符串头部和尾部的空格
String trim()
字符串长度
- 计算字符串长度
方法原型:
public int length() {
}
调用方法:
字符串标识符.length();
字符串
字符串比较
- equals判断字符串值相等,==判断字符串对象引用相等
示例代码:
public class StringDemo {
public static void main(String[] args) {
String str = "abc";
String str2 = new String("abc");
System.out.println(str == str2);// false
System.out.println(str.equals(str2));// true
}
}
内存结构图:
字符串连接
- 方法一:使用"+"
- 方法二:使用String类的concat()方法
String s = new String("你好,");
String name = new String("张三!");
String sentence = s.concat(name);
System.out.println(sentence);
// A.concat(B);
// B字符串将被连接到A字符串后面
// 输出结果:你好,张三!
字符串常用提取方法
- 常用提取方法举例
返回出现第一个匹配的位置,如果没有找到字符或字符串,则返回-1。
方法 | 说明 |
---|---|
public int indexOf(int ch) | 搜索第一个出现的字符ch |
public int indexOf(String value) | 搜索第一个出现的字符串value |
public int lastIndexOf(int ch) | 搜索最后一个出现的字符ch |
public int lastIndexOf(String value) | 搜索最后一个出现的字符串value |
public String substring(int index) | 提取从位置索引开始的字符串部分 |
public String substring(int beginindex, int endindex) | 提取beginindex和endindex之间的字符串部分 |
public String trim() | 返回一个前后不含任何空格的调用字符串的副本 |
小练习:如果要打印输出“小鱼儿”,应填入的代码是什么?
String word = "Hello, ";
word = word.trim();
String s = word.concat("小鱼儿!");
int index1 = s.index(',');
int index2 = s.index('!');
System.out.println(s.substring(____,____));
// 填入的结果是index1+1和index2
字符串拆分
问题: 有一段歌词,每句都以空格“ ”结尾,请将歌词每句按行输出。
String类提供了split()方法,将一个字符串分割为子字符串,结果作为字符串数组返回。
原歌词格式:
长亭外 古道边 芳草碧连天 晚风扶 柳笛声残 夕阳山外山
拆分后歌词格式:
长亭外
古道边
芳草碧连天
晚风扶
柳笛声残
夕阳山外山
示例代码:
public class Test {
public static void main(String[] args) {
String s = "长亭外 古道边 芳草碧连天 晚风扶 柳笛声残 夕阳山外山";
String[] s1 = s.split(" ");
for (String s2 : s1) {
System.out.println(s2);
}
}
}
StringBuffer类和StringBuilder类
- StringBuffer:String增强版,字符串缓冲区,是一个容器。
StringBuffer声明:
StringBuffer sb = new StringBuffer();// 创建空StringBuffer对象
StringBuffer sb = new StringBuffer("aaa");// 创建一个变量存储字符串aaa
StringBuffer的使用:
sb.toString();// 转换为String类型
sb.append("*");// 追加字符串
示例代码:
public class Test {
public static void main(String[] args) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(1).append(1.234).append("abc").append(true);
System.out.println(stringBuffer);// 11.234abctrue
System.out.println(stringBuffer.length());// 13
System.out.println(stringBuffer.capacity());// 16
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("123").append(1).append(false);
System.out.println(stringBuilder);// 1231false
}
}
字符串选用
- String:不可变字符序列
- StringBuilder:可变字符序列、效率高、线程不安全
- StringBuffer:可变字符序列、效率低、线程安全
- String使用陷阱:
1、String s = “a”;// 创建了一个字符串
2、s = s + “b”;// 实际上原来的"a"字符串对象已经丢弃了,现在又产生了一个字符串s + “b”。如果多次执行这些改变串内容的操作,会导致大量副本字符串对象存留在内存中,降低效率。如果这样的操作放在循环中,会极大影响程序的性能。
四、时间相关处理类
Date时间类(java.util.Date)
Date类:表示日期和时间。
提供操作日期和时间各组成部分的方法。
DateFormat类与SimpleDateFormat类
用于定制日期时间的格式。
示例代码:
public class DateDemo {
public static void main(String[] args) throws ParseException {
Date date = new Date();
System.out.println(date);
System.out.println(date.getTime());
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//将Date类按照规范转换为字符串格式
String str = dateFormat.format(date);
System.out.println(str);
//将字符串转换成对应的日期类
Date d1 = dateFormat.parse("2222-2-22 22:22:22");
System.out.println(d1);
}
}
// 输出的结果是:
// Mon Mar 04 21:21:18 HKT 2024
// 1709558478903
// 2024-03-04 21:21:18
// Fri Feb 22 22:22:22 HKT 2222
Calender
Calender类:抽象类,用于设置和获取日期/时间数据的特定部分。
Calender类提供一些方法和静态字段来操作日历。
方法或属性 | 说明 |
---|---|
int get(int field) | 返回给定日历字段的值 |
MONTH | 指示月 |
DAY_OF_MONTH | 指示一个月中的某天 |
DAY_OF_WEEK | 指示一个星期中的某天 |
示例代码:
public class DateDemo {
public static void main(String[] args) {
//获取的是当前系统的时间
Calendar calendar = Calendar.getInstance();
//设置指定时间的日历类
System.out.println(calendar);
System.out.println(calendar.get(calendar.YEAR));
System.out.println(calendar.get(calendar.MONTH));
System.out.println(calendar.get(calendar.DAY_OF_MONTH));
System.out.println(calendar.get(calendar.HOUR_OF_DAY));
System.out.println(calendar.get(calendar.MINUTE));
System.out.println(calendar.get(calendar.SECOND));
}
}
// 输出的结果是:
// java.util.GregorianCalendar[time=1709558632898,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Hong_Kong",offset=28800000,dstSavings=0,useDaylight=false,transitions=71,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=1,ERA=1,YEAR=2024,MONTH=2,WEEK_OF_YEAR=10,WEEK_OF_MONTH=2,DAY_OF_MONTH=4,DAY_OF_YEAR=64,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=23,SECOND=52,MILLISECOND=898,ZONE_OFFSET=28800000,DST_OFFSET=0]
// 2024
// 2
// 4
// 21
// 23
// 52
五、Math类
- 包含了常见的数学运算函数。
- random()->生成[0,1)之间的随机浮点数
- 生成:0-10之间的任意整数:
int a = (int)(10*Math.random());
- 生成:20-30之间的任意整数:
int b = 20 + (int)(10*Math.random());
示例代码:
public class Test {
public static void main(String[] args) {
System.out.println(Math.abs(-1));//取绝对值 1
System.out.println(Math.sqrt(2));//取根号 1.4142135623730951
System.out.println(Math.ceil(-3.14));//向上取整 -3.0
System.out.println(Math.floor(-3.14));//向下取整 -4.0
System.out.println(Math.pow(2,3));//取次方 8.0
}
}
六、枚举
概念:枚举指由一组固定的常量组成的类型。
使用枚举的好处
- 类型安全
- 易于输出
- 代码清晰
性别枚举:
public enum Gender {
男,女
}
枚举类型的变量:
public class Student {
public Gender sex;
}
Student stu = new Student();
stu.sex = Gender.男;
// 错误写法
stu.sex = "你好";
枚举类型:
1、只能够取特定值中的一个。
2、使用enum关键字。
3、所有的枚举类型隐性地继承自java.lang.Enum。(枚举实质上还是类!而每个被枚举的成员实质就是一个枚举类型的实例,他们默认都是public static final的。可以直接通过枚举类型名直接使用它们。)
4、强烈建议当你需要定义一组变量时,使用枚举类型。
实例代码:
public enum EventEnum {
LAUNCH("launch"),PAGEVIEW("pageview"),EVENT("event");
private String name;
EventEnum(String name) {
this.name = name;
}
public void show(){
System.out.println(this.name);
EventEnum[] ee = values();
for(int i = 0;i < ee.length;i++){
System.out.println(ee[i]);
}
}
}
测试代码:
public class Test {
public static void main(String[] args) {
EventEnum ee = EventEnum.LAUNCH;
ee.show();
String name = EventEnum.PAGEVIEW.name();
System.out.println(name);
}
}
// 输出的结果是:
// launch
// LAUNCH
// PAGEVIEW
// EVENT
// PAGEVIEW