第二章 实用类介绍
一、枚举
1.写法 public enum(关键字) 名字{
定义的常量
}
2.
枚举可以有字段、方法和构造函数。构造函数是私有的,因为枚举的实例是固定的。
public enum Day {
//定义常量,并且有内容
SUNDAY("Weekend"),
MONDAY("Weekday"),
TUESDAY("Weekday"),
WEDNESDAY("Weekday"),
THURSDAY("Weekday"),
FRIDAY("Weekday"),
SATURDAY("Weekend");
private String type; //定义
//构造方法,为常量的内容赋值初始化
Day(String type) {
this.type = type;
}
//其他方法调用,获取信息
public String getType() {
return type;
}
}
public class Main {
public static void main(String[] args) {
Day day = Day.SUNDAY;
System.out.println(day + " is a " + day.getType());
//for增强循环打印
for (Day day : Day.values()) //values() 是一个静态方法,它返回一个包 含枚举类型中所有常量的数组
{
System.out.println(day + ": " + day.getType());
}
}
}
调用:
1.Student.learningcontent.L1.getLearnstudy()
可以直接通过类名.枚举名称.常量.常量内容
2.Student stu=new Student();
stu.type=Day.SUNDAY;//根据上面的代码
也可以通过实例化对象,调用属性
二、Java的包装类型
在Java中,包装类型是用于将基本数据类型(如`int`、`char`、`float`等)包装成对象的类。这些包装类允许基本数据类型像对象一样操作。Java中的包装类型都位于`java.lang`包中。
Java为每个基本数据类型提供了一个对应的包装类型:
byte
->Byte
short
->Short
int
->Integer
long
->Long
float
->Float
double
->Double
char
->Character
boolean
->Boolean
一、主要作用
1.对象的使用:
某些Java集合(如ArrayList
、HashMap
)只能存储对象,而不能直接存储基本数据类型。通过包装类型,可以将基本数据类型包装成对象后存储在集合中。
ArrayList<Integer> list = new ArrayList<>();
list.add(10); // 自动装箱
Boolean类构造方法参数为String类型时,若该字符串内容为true(不考虑大小写),则该Boolean对象表示true,否则表示false
Boolean b4 = new Boolean("anyOtherString"); // b4 为 false
当Number包装类构造方法参数为String 类型时,字符串不能为null,且该字符串必须可解析为相应的基本数据类型的数据,否则编译不通过,运行时会抛出NumberFormatException
异常
Integer invalidInt = new Integer("abc"); // 会抛出 NumberFormatException,因为abc不能转化为数字
2.用于泛型编程:
由于Java的泛型机制不支持基本数据类型,使用包装类型可以绕过这个限制。例如,List<int>
是非法的,但List<Integer>
是合法的。
二、常用方法
1.Value()
包装类转换成基本类型
Integer integerId=new Integer(25);
int intId=integerId.intValue();
2.toString()
基本类型->字符串
以字符串形式返回包装对象表示的基本类型数据
public static void main(String[] args) {
// 创建一个 Integer 类型的包装类对象
Integer num = new Integer(123);
// 使用 toString() 方法将包装类对象转换为字符串
String str = num.toString();
// 输出转换后的字符串
System.out.println("转换后的字符串: " + str);
}
主要作用进行字符串的拼接
3.parseXXX()
把字符串转换为相应的基本数据类型数据(Character除外)(字符串->基本类型)
将字符串 s 解析为 int 基本数据类型。
int num=Integer.parseInt("36");
将字符串 s 解析为 boolean 基本数据类型。
boolean bool=Boolean.parseBoolean("false");
4.valueOf()
用于将不同类型的数据转换为对应的包装类对象
对于整数类型(int),可以使用 Integer.valueOf() 将其转换为 Integer 对象;
对于浮点数类型(double),可以使用 Double.valueOf() 将其转换为 Double 对象。 //自动装箱
// 将 int 转换为 Integer
int num = 42;
Integer integerObj = Integer.valueOf(num);
// 将 double 转换为 Double
double d = 3.14;
Double doubleObj = Double.valueOf(d);
三、自动装箱与拆箱
1.自动装箱(Autoboxing)
将基本数据类型自动转换为对应的包装类型。例如,将int
转换为Integer
。
Integer num = 5; // 自动装箱,将int 5转换为Integer
2.自动拆箱(Unboxing)
将包装类型自动转换为对应的基本数据类型。例如,将Integer
转换为int
。
int n = num; // 自动拆箱,将Integer对象转换为int
四、Math类
1.Math.abs(-3.5)
求绝对值
2.Math.max(2.5, 90.5)
;
求最大值
3.int random = (int) (Math.random() * 10)
生成一个0-9之间的随机数
4.随机数的其他方式
Random rand=new Random(); //创建一个Random对象
int num=rand.nextInt(10);//返回下一个伪随机数,整型的
num就是生成的随机数字
int randomNumber = rand1.nextInt(16) + 20; // 生成20-35之间的随机整数
System.out.println("随机数: " + randomNumber);
//
int randomNumber1 = rand1.nextInt(51) + 50; // 生成50-100之间的随机整数
System.out.println("随机数: " + randomNumber1);
五、String类
String类位于java.lang包中,具有丰富的方法
1.length()
方法
返回字符串中的字符数(包括空格和标点符号)
String word = "Hello,World";
System.out.println(word.length());
打印的结果是 11
2.equals()
方法
== 运算符
作用: ==用于比较两个变量的内存地址,即判断两个对象是否引用同一个内存位置(栈)。
适用场景: ==通常用于比较基本数据类型(如int, char, boolean等)和对象引用。
"=="进行比较会返回true。
int a = 5;
int b = 5;
System.out.println(a == b); // 输出 true,因为两个基本数据类型的值相等
String str1 = new String("hello");
String str2 = new String("hello");
System.out.println(str1 == str2); // 输出 false,因为str1和str2引用了不同的内存位置
String str3 = "hello";
String str4 = "hello";
System.out.println(str3 == str4); // 输出 true,因为str3和str4引用了同一个字符串常量池中的对象
equals()用于比较两个对象的内容是否相同,而不是它们的内存地址
String str1 = new String("hello");
String str2 = new String("hello");
System.out.println(str1.equals(str2)); // 输出 true,因为str1和str2的内容相同
重写equals() 方法
public boolean equals(Object obj){
if (s.name.equals(this.name)
&&s.age==this.age&&s.id==this.id) {
return true;
}
return false;
}
3.字符串比较的其他方法
使用equalsIgnoreCase()//忽略大小写
使用toLowerCase()小写//转换为小写
String word = "Hello,WORLD";
System.out.println(word.toLowerCase());
输出结果:hello,world
使用toUpperCase()大写//转换为大写
System.out.println(word.toUpperCase());
输出结果: HELLO,WORLD
4.字符串的拼接
1、使用“+”
String a="aaa";
String b="bbb";
String c=a+b;//拼接字符串
2、使用String类的concat()方法
String a="aaa";
String b="bbb";
String c=a.concat(b);
5.字符串的提取方法
1、indexOf(int ch)
String word = "Hello,World";
System.out.println(word.indexOf("l"));
从0开始,返回结果为2
2、lastIndexOf
System.out.println(word.lastIndexOf("o"));
返回结果为8
3、String c=word.substring(1,6);
返回结果:ello,//包含1,不包含6
4、trim()
String c="hello, "
System.out.println( c.trim());
返回结果:hello
六、StringBuffer类
常用的StringBuffer方法:
append():将指定的数据添加到当前StringBuffer对象的末尾。
insert():在指定位置插入指定的数据。
delete():删除从指定位置开始的指定长度的字符。
reverse():反转当前StringBuffer对象中的字符顺序。
capacity():返回当前StringBuffer对象的容量。
length():返回当前StringBuffer对象的长度。
setCharAt():将指定位置的字符替换为指定的字符。
charAt():返回指定位置的字符。
toString():将StringBuffer对象转换为String对象。
// 创建一个空的StringBuffer对象
StringBuffer sb = new StringBuffer();
// 使用append()方法添加字符串
sb.append("Hello");
sb.append(" ");
sb.append("World!");
// 输出结果
System.out.println(sb.toString()); // 输出:Hello World!
// 使用insert()方法插入字符串
sb.insert(6, " Java");
System.out.println(sb.toString()); // 输出:Hello Java World!
// 使用delete()方法删除字符
sb.delete(6, 10);
System.out.println(sb.toString()); // 输出:Hello World!
// 使用reverse()方法反转字符串
sb.reverse();
System.out.println(sb.toString()); // 输出:!dlroW olleH
String是不可变对象
经常改变内容的字符串最好不要使用String
StringBuffer是可变的字符串
七、Date类
/创建日期对象
Date date = new Date();
//定制日期格式
SimpleDateFormat formater = new SimpleDateFormat("yyyy- MM-dd HH:mm:ss");
String now = formater.format(date);
System.out.println(now); //打印现在时间
八、Calendar类
set方法:允许人们设置Calendar对象的年、月、日、时、分、秒等信息。
get方法:用于检索特定的日历字段值,例如年、月、日等。
setTime方法:允许将Date对象的时间设置为Calendar对象的当前时间。
getTime方法:返回表示Calendar对象当前时间的Date对象。
add方法:用于向指定的日历字段添加或减去指定的时间量,例如天数或小时数。
getTimeInMillis方法:返回Calendar对象表示的时间值,以毫秒为单位。
// 创建一个Calendar实例
Calendar calendar = Calendar.getInstance();
// 获取当前年份、月份和日期
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始,所以 需要加1
int day = calendar.get(Calendar.DAY_OF_MONTH);
// 设置日历的某个字段值
calendar.set(Calendar.YEAR, 2023);
calendar.set(Calendar.MONTH, Calendar.JANUARY); // 月份从0开始,所 以使用Calendar.JANUARY表示一月
calendar.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("设置后的日期: " + calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "日");
}//get获取日期时间
// 设置时间
calendar.setTime(new Date());
// 获取当前时间
Date currentDate = calendar.getTime();
System.out.println("Current date: " + currentDate);
// 添加时间量
calendar.add(Calendar.DAY_OF_MONTH, 5); // 增加5天
calendar.add(Calendar.HOUR_OF_DAY, -3); // 减少3小时
// 获取修改后的时间
Date modifiedDate = calendar.getTime();
System.out.println("Modified date: " + modifiedDate);
// 获取毫秒值
long millis = calendar.getTimeInMillis();
System.out.println("Milliseconds since January 1, 1970, 00:00:00 GMT: " + millis);
//输出结果
Current date: Mon Sep 02 16:05:58 CST 2024 //mon星期一
Modified date: Sat Sep 07 13:05:58 CST 2024 //sat 星期六