目录
包装类
包装类的分类
- 针对八种基本数据类型相应的引用类型 —— 包装类
- 有了类的特点,就可以调用类中的方法
基本数据类型 | 包装类 |
---|---|
boolean | Boolean |
char | Character |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
- 黄色的父类都是Number
包装类和基本数据类型的转换(装箱和拆箱)
- 演示包装类和基本数据类型的相互转换,这里以int和Integer演示
- 装箱:基本类型 -> 包装类型
- 拆箱:包装类型 -> 基本类型
- JDK5之前的手动装箱和拆箱方式
package com.zanedu.wrapper;
public class Integer01 {
public static void main(String[] args) {
//演示int <--> Integer的装箱和拆箱
//JDK5前时手动装箱和拆箱
//手动装箱 -> 将其基本数据类型 -> 包装类型 == int -> Integer
int n1 = 100;
Integer integer = new Integer(n1);//JDK17已经弃用这种方法了
Integer integer1 = Integer.valueOf(n1);
//手动拆箱
//Integer -> int
int i = integer.intValue();
}
}
- JDK5之后(含JDK5)的自动装箱和拆箱方式
package com.zanedu.wrapper;
public class Integer01 {
public static void main(String[] args) {
//演示int <--> Integer的装箱和拆箱
//JDK5后,就可以自动装箱和自动拆箱
int n2 = 200;
//自动装箱 int -> Integer
Integer integer2 = n2; //底层使用的是 Integer.valueOf(n2);
//自动拆箱 Integer -> int
int n3 = integer2; //底层仍然使用的是 intValue()方法
}
}
- 自动装箱底层调用的是valueOf方法,比如Integer.valueOf(),自动拆箱底层调用的是intValue()方法
- 自动装箱 - Integer.valueOf()
- 自动拆箱 - intValue()
- 其它包装类的用法类似
课堂测试题
package com.zanedu.wrapper;
public class WrapperExercise01 {
public static void main(String[] args) {
Double d = 100d; //ok, 自动装箱 Double.valueOf(100d);
Float f = 1.5f; //ok, 自动装箱 Float.valueOf(1.5f);
Object obj1 = true? new Integer(1) : new Double(2.0);//三元运算符【是一个整体】 一真大师
System.out.println(obj1);// 什么? 1.0
//三元运算符是一个整体,由于后面是double,所以精度会提升到double,因此最后输出为1.0
Object obj2;
if(true)
obj2 = new Integer(1);
else
obj2 = new Double(2.0);
System.out.println(obj2);//1
//输出什么 ? 1, 分别计算
}
}
包装类型和String类型的相互转换
package com.zanedu.wrapper;
public class WrapperVSString {
public static void main(String[] args) {
//包装类(Integer为例) -> String
Integer i = 100; //自动装箱
//方式一:
String str1 = i + "";//这个只是得到了一个字符串,但是对原先的 i 没有变化/影响
//方式二:
String str2 = i.toString();
//方式三:
String str3 = String.valueOf(i);
//String -> 包装类(Integer)
String str4 = "12345";
//方式一
int i2 = Integer.parseInt(str4);//使用到自动装箱
//方式二
Integer i3 = new Integer(str4);//构造器
System.out.println("ok");
}
}
Integer类和Character类的常用方法
- Integer类和Character类有些常用的方法
package com.zanedu.wrapper;
public class WrapperMethod {
public static void main(String[] args) {
System.out.println(Integer.MIN_VALUE); //返回最小值
System.out.println(Integer.MAX_VALUE);//返回最大值
System.out.println(Character.isDigit('a'));//判断是不是数字
System.out.println(Character.isLetter('a'));//判断是不是字母
System.out.println(Character.isUpperCase('a'));//判断是不是大写
System.out.println(Character.isLowerCase('a'));//判断是不是小写
System.out.println(Character.isWhitespace('a'));//判断是不是空格
System.out.println(Character.toUpperCase('a'));//转成大写
System.out.println(Character.toLowerCase('A'));//转成小写
}
}
Integer类面试题
package com.zanedu.wrapper;
public class WrapperExercise02 {
public static void main(String[] args) {
Integer i = new Integer(1);
Integer j = new Integer(1);
//这里是直接创建了对象,没有装箱,因此指向两个不同的对象
System.out.println(i == j); //False
//Integer.valueOf()的源码
//看完源码,发现这里主要是看范围 -128 ~ 127 就是直接返回
/*
老韩解读
//1. 如果i 在 IntegerCache.low(-128)~IntegerCache.high(127),就直接从数组返回
//2. 如果不在 -128~127,就直接 new Integer(i)
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
*/
Integer m = 1; //底层 调用了Integer.valueOf(1); -> 阅读源码
Integer n = 1;//底层 调用了Integer.valueOf(1);
System.out.println(m == n); //T
//所以,这里主要是看范围 -128 ~ 127 就是直接返回
//,否则,就new Integer(xx);
Integer x = 128;//底层Integer.valueOf(1);
Integer y = 128;//底层Integer.valueOf(1);
System.out.println(x == y);//False
}
}
- 查看Integer.valueOf()的源码
- 发现在 low 和 high 范围内,就是直接返回,而不是创建 Integer对象
- 而 low 和 high 的范围就是 [-128, 127]
Integer类面试题总结
package com.zanedu.wrapper;
public class WrapperExercise03 {
public static void main(String[] args) {
//示例一
Integer i1 = new Integer(127);
Integer i2 = new Integer(127);
System.out.println(i1 == i2);//F
//示例二
Integer i3 = new Integer(128);
Integer i4 = new Integer(128);
System.out.println(i3 == i4);//F
//示例三
Integer i5 = 127;//底层Integer.valueOf(127)
Integer i6 = 127;//-128~127
System.out.println(i5 == i6); //T
//示例四
Integer i7 = 128;
Integer i8 = 128;
System.out.println(i7 == i8);//F
//示例五
Integer i9 = 127; //Integer.valueOf(127)
Integer i10 = new Integer(127);
System.out.println(i9 == i10);//F
//示例六
Integer i11 = 127;
int i12 = 127;
//只要有基本数据类型,判断的是值是否相同
System.out.println(i11==i12); //T
//示例七
Integer i13=128;
int i14=128;
System.out.println(i13==i14);//T
}
}
- 注意:只要有基本数据类型,那么判断的就是值是否相同
String类
String类的理解和创建对象
- String类的父类和实现接口
- 分析:由于实现了Serializable接口,因此说明String可以串行化,而串行化就是可以在网络上传播
- String对象用于保存字符串,也就是一组字符序列
- 字符串常量对象是用双引号括起的字符序列。例如:“你好”、“12.97”、"boy"等
- 字符串的字符使用Unicode字符编码,一个字符(无论字母还是汉字)占****两个字节
- String类较常用的几个常用构造器(其他的看JDK文档)
a)String s1 = new String();
b)String s2 = new String(String original);
c)String s3 = new String(char[] a);
d)String s4 = new String(char[] a, int startIndex, int count);
- String类实现了****接口 Serializable [String可以串行化,可以在网络传播]
String类实现了****接口 Comparable [String对象可以相互比较大小]
- String类是final类,不能被其他的类继承
- String类有属性 private final char value[]****:用于存放字符串内容
- 一定要注意:value[] 是一个final类型,不可修改【地址不可修改,但是可以修改数值】即 value[] 不能指向新的地址,但是单个字符内容可以改变
package com.zanedu.string_;
public class String01 {
public static void main(String[] args) {
//1. String 对象用于保存字符串,也就是一组字符序列
//2. "jack" 字符串常量,用双引号括起来的字符序列
//3. 字符串的字符使用Unicode字符编码,一个字符(不区分字母还是汉字)都占两个字节
//4. String 类有很多构造器,构造器的重载
// 常用的有
/*
String s1 = new String();
String s2 = new String(String original);
String s3 = new String(char[] a);
String s4 = new String(char[] a, int startIndex, int count);
String s5 = new String(byte[] b);
*/
//5. String类实现了接口 Serializable [String可以串行化:可以在网络传输]
// 接口 Comparable [String对象可以相互比较大小]
//6. String 类是final类,不能被其他的类继承
//7. String 有属性 private final char value[] :用于存放字符串内容
//8. 一定要注意:value是一个final类型,不可修改【地址不可修改,可以修改数值】
// 即value不能指向新的地址,但是单个字符内容可以变化
String name = "jack";
name = "tom";
final char[] value = {'a', 'b', 'c'};
char[] v2 = {'t', 'o', 'm'};
value[0] = 'H';
// value = v2;//error 不能修改value的地址
}
}
创建String对象的两种方式
方式一:直接赋值:String s = “zan”;
方式二:调用构造器:String s = new String(“zan”);
两种创建String对象的区别
**方式一:先从常量池查看是否有"zan"数据空间,如果有,直接指向即可;如果没有则会创建一个"zan"对象,然后指向。**因此s最终指向的是常量池的空间地址
**方式二:先从堆中创建空间,里面维护了value属性,value指向常量池的"zan"空间,如果常量池没有"zan"空间,则会创建"zan"空间,如果有,直接通过value指向,**因此s2最终指向的是堆中的空间地址
课堂测试题
测试题1
package com.zanedu.string_;
public class StringExercise01 {
public static void main(String[] args) {
String a = "abc";
String b = "abc";
System.out.println(a.equals(b));//T
System.out.println(a == b);//T
}
}
- 第一个就是字符串相比,一个一个字符比较过去
- 第二个就是比较地址是否相等,即看指向的对象是否一致,而a,b都是直接赋值方法,即都指向常量池的对象
测试题2
package com.zanedu.string_;
public class StringExercise02 {
public static void main(String[] args) {
String a = new String("abc");
String b = new String("abc");
System.out.println(a.equals(b));//T
System.out.println(a == b);//F
}
}
- 第一个同上
- 第二个也同上,不同的就是a,b的创建String对象的形式不同,这里的创建对象的形式是调用构造器,即最后指向的都是在堆中的对象,而都是创建了对象,即指向不同的对象
测试题3
package com.zanedu.string_;
public class StringExercise03 {
public static void main(String[] args) {
String a = "zan";//a指向常量池的"zan"
String b = new String("zan");//b指向堆中的对象
System.out.println(a.equals(b));//T
System.out.println(a == b);//F
System.out.println(a == b.intern());//T
System.out.println(b == b.intern());//F
}
}
- 知识点:
当调用 intern 方法时,如果池已经包含一个等于此 String 对象的字符串(用equals(Object)方法确定),则返回池中的字符串。否则,将此String对象添加到池中,并返回此 String 对象的引用
解读:****.intern()方法最终返回的是常量池的地址(对象)
- 分析:最后两个的b.intern()返回的就是b指向常量池的地址/对象,而a指向的就是常量池的对象,即true,而b指向的是堆中的对象,即false
测试题4
package com.zanedu.string_;
public class StringExercise04 {
public static void main(String[] args) {
String s1 = "hspedu"; //指向常量池”hspedu”
String s2 = "java"; //指向常量池”java”
String s3 = new String("java");//指向堆中对象
String s4 = "java";//指向常量池”java”
System.out.println(s2 == s3); //F
System.out.println(s2 == s4); //T
System.out.println(s2.equals(s3)); //T
System.out.println(s1 == s2); //F
}
}
测试题5
package com.zanedu.string_;
public class StringExercise05 {
public static void main(String[] args) {
Person p1 = new Person();
p1.name = "zanedu";
Person p2 = new Person();
p2.name = "zanedu";
System.out.println(p1.name.equals(p2.name));//比较内容: True
System.out.println(p1.name == p2.name); //T
System.out.println(p1.name == "zanedu"); //T
String s1 = new String("bcde");
String s2 = new String("bcde");
System.out.println(s1==s2); //False
}
}
class Person {
public String name;
}
字符串的特性
基本说明
- String是一个final类,代表不可变的字符序列
- 字符串是不可变的,一个字符串对象一旦被分配,其内容是不变的
- 问:一下语句创建了几个对象?//两个对象
String s1 = “hello”;
s1 = “haha”;
- 解读:当s1 = “haha"时,会先去池子里找有没有"haha”,如果有就直接指向,如果没有,就创建"haha",然后重新指向,而指向"hello"的线就断掉了,但是"hello"仍然在常量池中
面试题
题一
String a = “hello” + “abc”;
问:创建了几个对象? // 只有1个对象
- 解读:
String a = “hello” + “abc”; ==> 优化等价于 String a = “helloabc”
编译器不傻,会做一个优化,判断创建的常量池对象,是否有引用指向
题二
package com.zanedu.string_;
public class StringExercise08 {
public static void main(String[] args) {
String a = "hello";//创建a对象
String b = "abc";//创建b对象
//解读
/*
1. 先创建一个StringBuilder sb = StringBuilder()
2. 执行 sb.append("hello") ,这个就是追加hello
3. 继续执行 sb.append("abc")
4. 再调用sb.toString方法,返回helloabc字符串
最后其实是 c 指向堆中的对象(String) value[] -> 池中 "helloabc"
*/
//问:String c = a + b 创建了几个对象
String c = a + b;//到时候画图可以使用debug一步一步进去看
//创建了3个对象
String d = "helloabc";
System.out.println(c == d);//false
String e = "hello" + "abc";//直接看池,e指向常量池
System.out.println(d == e);//true
}
}
小结:
- 底层是先创建一个StringBuilder sb = StringBuilder()
- 然后执行sb.append(a);
- 再执行 sb.append(b);
- sb是在堆中,并且append是在原来的字符串的基础上追加的
重要规则:String c1 = “ab” + “cd”; 是常量相加,看的是池
String c1 = a + b; 是变量相加,是在堆中
题三
package com.zanedu.string_;
public class StringExercise09 {
public static void main(String[] args) {
String s1 = "hspedu"; //s1 指向池中的 “hspedu”
String s2 = "java"; // s2 指向池中的 “java”
String s5 = "hspedujava"; //s5 指向池中的 “hspedujava”
String s6 = (s1 + s2).intern();//s6 指向池中的 “hspedujava”
System.out.println(s5 == s6); //T
System.out.println(s5.equals(s6));//T
}
}
题四
- 下列程序运行的结果是什么?
package com.zanedu.string_;
public class StringExercise10 {
}
class Test1 {
String str = new String("hsp");
final char[] ch = {'j', 'a', 'v', 'a'};
public void change(String str, char ch[]) {
str = "java";
ch[0] = 'h';
}
public static void main(String[] args) {
Test1 ex = new Test1();
ex.change(ex.str, ex.ch);
System.out.print(ex.str + " and ");
System.out.println(ex.ch);
}
}
- 画图分析
String类的常见方法
基本说明
String类是保存字符串常量的,每次更新都需要重新开辟空间,效率较低,因此java设计者还提供了StringBuilder和StringBuffer来增强String的功能,并提高效率
String s = new String("");
for (int i = 0; i < 80000; i++) {
s += "hello";
}
- 这里我们发现每加上一次,都要重新在常量池里开辟空间,这样就会使得效率低下
String类的常见方法一览
equals:区分大小写,判断内容是否相等
equalsIgnoreCase:忽略大小写的判断内容是否相等
length:获取字符的个数、字符串的长度
indexOf:获取字符在字符串第1次出现的索引,索引从0开始,如果找不到,则返回-1
lastIndexOf:获取字符在字符串中最后1次出现的索引,索引从0开始,如果找不到,返回-1
substring:截取指定范围的子串
trim:去前后空格
**charAt:获取某索引处的字符,**注意不能使用Str[index]这种方式
package com.zanedu.string_;
public class StringMethod01 {
public static void main(String[] args) {
//1. equals 前面已经讲过了. 比较内容是否相同,区分大小写
String str1 = "hello";
String str2 = "Hello";
System.out.println(str1.equals(str2));//False
// 2.equalsIgnoreCase 忽略大小写的判断内容是否相等
String username = "johN";
if ("john".equalsIgnoreCase(username)) {
System.out.println("Success!");
} else {
System.out.println("Failure!");
}
// 3.length 获取字符的个数,字符串的长度
System.out.println("韩顺平".length());
// 4.indexOf 获取字符在字符串对象中第一次出现的索引,索引从0开始,如果找不到,返回-1
String s1 = "wer@terwe@g";
int index = s1.indexOf('@');
System.out.println(index);// 3
//也可以查找字符串,也是第一次出现的索引
System.out.println("weIndex=" + s1.indexOf("we"));//0
// 5.lastIndexOf 获取字符在字符串中最后一次出现的索引,索引从0开始,如果找不到,返回-1
s1 = "wer@terwe@g@";
index = s1.lastIndexOf('@');
System.out.println(index);//11
System.out.println("ter的位置=" + s1.lastIndexOf("ter"));//4
// 6.substring 截取指定范围的子串
String name = "hello,张三";
//下面name.substring(6) 从索引6开始截取后面所有的内容
System.out.println(name.substring(6));//截取后面的字符
//name.substring(0,5)表示从索引0开始截取,截取到索引为 5-1=4位置
System.out.println(name.substring(0, 5));//截取5个字符
System.out.println(name.substring(2, 5));//llo
}
}
toUpperCase:转换成大写
toLowerCase:转换成小写
concat:拼接字符串
replace:替换字符串中的字符
split:分割字符串,对于某些分割字符,我们需要转义 比如:| \等
compareTo:比较两个字符串的大小
toCharArray:转换成字符数组
format:格式化字符串
package com.zanedu.string_;
public class StringMethod02 {
public static void main(String[] args) {
// 1.toUpperCase转换成大写
String s = "heLLo";
System.out.println(s.toUpperCase());//HELLO
// 2.toLowerCase转换成小写
System.out.println(s.toLowerCase());//hello
// 3.concat拼接字符串
String s1 = "宝玉";
s1 = s1.concat("林黛玉").concat("薛宝钗").concat("together");
System.out.println(s1);//宝玉林黛玉薛宝钗together
// 4.replace 替换字符串中的字符
s1 = "宝玉 and 林黛玉 林黛玉 林黛玉";
//在s1中,将 所有的 林黛玉 替换成薛宝钗
//s1.replace("林黛玉", "薛宝钗");
// 解读: s1.replace() 方法执行后,返回的结果才是替换过的.
// 注意对 s1没有任何影响
String s11 = s1.replace("宝玉", "jack");
System.out.println(s1);//宝玉 and 林黛玉 林黛玉 林黛玉
System.out.println(s11);//jack and 林黛玉 林黛玉 林黛玉
// 5.split 分割字符串, 对于某些分割字符,我们需要 转义比如 | \\等
String poem = "锄禾日当午,汗滴禾下土,谁知盘中餐,粒粒皆辛苦";
String[] split = poem.split(",");
//老韩解读:
// 1. 以 , 为标准对 poem 进行分割 , 返回一个数组
// 2. 在对字符串进行分割时,如果有特殊字符,需要加入 转义符 \
System.out.println("===这首诗的内容是===");
for (int i = 0; i < split.length; i++) {
System.out.println(split[i]);
}
poem = "E:\\aaa\\bbb";
split = poem.split("\\\\");
System.out.println("==分割后内容===");
for (int i = 0; i < split.length; i++) {
System.out.println(split[i]);
}
// 6.toCharArray 转换成字符数组
s = "happy";
char[] chs = s.toCharArray();
for (int i = 0; i < chs.length; i++) {
System.out.println(chs[i]);
}
// 7.compareTo 比较两个字符串的大小,如果前者大,
// 则返回正数,后者大,则返回负数,如果相等,返回0
// 解读
// (1) 如果长度相同,并且每个字符也相同,就返回 0
// (2) 如果长度相同或者不相同,但是在进行比较时,可以区分大小
// 就返回 if (c1 != c2) {
// return c1 - c2;
// }
// (3) 如果前面的部分都相同,就返回 str1.len - str2.len
String a = "jcck";
String b = "jack";// len = 4
String c = "jac";// len = 3
System.out.println(c.compareTo(b));// 3 - 4 = -1
System.out.println(a.compareTo(b)); // 返回值是 'c' - 'a' = 2的值
// 8.format 格式字符串
/* 占位符有:
* %s 字符串 %c 字符 %d 整型 %.2f 浮点型
*
*/
String name = "john";
int age = 10;
double score = 56.857;
char gender = '男';
//将所有的信息都拼接在一个字符串.
String info =
"我的姓名是" + name + "年龄是" + age + ",成绩是" + score + "性别是" + gender + "。希望大家喜欢我!";
String info3 = String.format("我的姓名是%s 年龄是%d,成绩是%.2f 性别是%c.希望大家喜欢我!", name, age, score, gender);
System.out.println(info);
//解读
//1. %s , %d , %.2f %c 称为占位符
//2. 这些占位符由后面变量来替换
//3. %s 表示后面由 字符串来替换
//4. %d 是整数来替换
//5. %.2f 表示使用小数来替换,替换后,只会保留小数点两位, 并且进行四舍五入的处理
//6. %c 使用char 类型来替换
String formatStr = "我的姓名是%s 年龄是%d,成绩是%.2f 性别是%c.希望大家喜欢我!";
String info2 = String.format(formatStr, name, age, score, gender);
System.out.println("info2=" + info2);
}
}
StringBuffer类
基本介绍
- java.lang.StringBuffer代表可变的字符序列,可以对字符串内容进行增删
- 很多方法与String相同,但是StringBuffer是可变长度的
- StringBuffer是一个容器
package com.zanedu.stringbuffer_;
public class StringBuffer01 {
public static void main(String[] args) {
//解读
/*
1. StringBuffer的直接父类是 AbstractStringBuilder
2. StringBuffer 实现了 Serializable接口,即StringBuffer的对象可以串行化
3. 在父类中 AbstractStringBuilder 有属性 char[] value ,不是final
该value 数组存放 字符串内容,引出存放在堆中的,不在常量池了
4. StringBuffer 是一个final类,不能被继承
5. 因为 StringBuffer 字符内容是存在char[] value ,所以再变化(增加/删除)时,不用每次都更换地址(即创建新的对象)
*/
StringBuffer stringBuffer = new StringBuffer();
}
}
package com.zanedu.stringbuffer_;
public class StringBuffer02 {
public static void main(String[] args) {
//构造器的使用
//解读
//1. 创建一个大小为16的char[] ,用于存放字符内容
StringBuffer stringBuffer = new StringBuffer();
//2. 通过构造器指定char[] 大小
StringBuffer stringBuffer1 = new StringBuffer(100);
//3. 通过给一个String 创建 StringBuffer, char[] 大小就是str.length() + 1
StringBuffer hello = new StringBuffer("hello");
}
}
String VS StringBuffer
- String保存的是字符串常量,里面的值不能更改,每次String类的更新实际上就是更改地址,效率较低 // private final char value[];
- StringBuffer保存的是字符串变量,里面的值可以更改,每次StringBuffer的更新实际上可以更新内容,不用每次更新地址,效率较高 // char[] value; 这个是放在堆中的
- String在常量池里,一旦改变了,就会产生一个新的内容,再重新指向
- 在堆中只有当空间不够时,才会扩展更新地址,不用每次都更新
String 和 StringBuffer 相互转换
package com.zanedu.stringbuffer_;
public class StringAndStringBuffer {
public static void main(String[] args) {
//看 String --> StringBuffer
String str = "hello tom";
//方式一:使用构造器
//注意:返回的才是StringBuffer对象,对str本身没有影响
StringBuffer stringBuffer = new StringBuffer(str);
//方式二:使用的是append方法
StringBuffer stringBuffer1 = new StringBuffer();
stringBuffer1 = stringBuffer1.append(str);
//看 StringBuffer --> String
StringBuffer stringBuffer3 = new StringBuffer("zan教育");
//方式一:使用StringBuffer提供的 toString方法
String s = stringBuffer3.toString();
//使用构造器来搞定
String s1 = new String(stringBuffer3);
}
}
StringBuffer类常见方法
package com.zanedu.stringbuffer_;
public class StringBufferMethod {
public static void main(String[] args) {
StringBuffer s = new StringBuffer("hello");
//增
s.append(',');// "hello,"
s.append("张三丰");//"hello,张三丰"
s.append("赵敏").append(100).append(true).append(10.5);//"hello,张三丰赵敏100true10.5"
System.out.println(s);//"hello,张三丰赵敏100true10.5"
//删
/*
* 删除索引为>=start && <end 处的字符
* 解读: 删除 11~14的字符 [11, 14)
*/
s.delete(11, 14);
System.out.println(s);//"hello,张三丰赵敏true10.5"
//改
//解读,使用 周芷若 替换 索引9-11的字符 [9,11)
s.replace(9, 11, "周芷若");
System.out.println(s);//"hello,张三丰周芷若true10.5"
//查找指定的子串在字符串第一次出现的索引,如果找不到返回-1
int indexOf = s.indexOf("张三丰");
System.out.println(indexOf);//6
//插
//解读,在索引为9的位置插入 "赵敏",原来索引为9的内容自动后移
s.insert(9, "赵敏");
System.out.println(s);//"hello,张三丰赵敏周芷若true10.5"
//长度
System.out.println(s.length());//22
System.out.println(s);
}
}
StringBuffer类课后练习
题一
package com.zanedu.stringbuffer_;
public class StringBufferExercise01 {
public static void main(String[] args) {
String str = null;
StringBuffer sb = new StringBuffer();//ok
sb.append(str);//需要看源码,底层调用的时AbstractStringBuilder 的 appendNull
System.out.println(sb.length());//4
System.out.println(sb);//null
//下面的构造器,会抛出NullPointException
StringBuffer sb1 = new StringBuffer(str);//看底层源码 super(str.length() + 16);
System.out.println(sb1);
}
}
- 看源码我们发现,当他为null空指针的时候,会将null存入数组
- 而后面的sb1,我们发现源码是str.length() + 16,但是str是null空指针,因此会抛出空指针异常
题二
输入商品名称和商品价格,要求打印效果示例,使用前面学习的方法完成
要求:价格的小数点前面每三位用逗号隔开,在输出,即123,564.59
package com.zanedu.stringbuffer_;
public class StringBufferExercise02 {
public static void main(String[] args) {
// 输入商品名称和商品价格,要求打印效果示例, 使用前面学习的方法完成:
// 商品名 商品价格
// 手机 123,564.59 //比如 价格 3,456,789.88
//
//要求:价格的小数点前面每三位用逗号隔开, 在输出。
/*
分析:
1. 定义一个 Scanner对象,接受用户输入的价格(String)
2. 希望使用到 StringBuffer 的insert,需要将 String 转成 StringBuffer
3. 然后使用相关方法进行字符串的处理
*/
String price = "8123564.59";
StringBuffer sb = new StringBuffer(price);
//先完成一个最简单的实现123,564.59
//找到小数点的索引,然后在该位置的前三位插入逗号即可
// int i = sb.lastIndexOf(".");
// sb = sb.insert(i - 3, ',');
//上面的两步需要做一个循环处理,才是正确的
for (int i = sb.lastIndexOf(".") - 3; i > 0; i -= 3) {
sb = sb.insert(i, ',');
}
System.out.println(sb);//8,123,564.59
}
}
StringBuilder类
基本介绍
- 一个可变的字符序列,此类提供一个与StringBuffer兼容的API,但不保证同步(StringBuilder不是线程安全)。该类被设计用作StringBuffer的一个简易替换,用在字符串缓冲区被单个线程使用的时候,如果可能,建议优先采用该类。因为在大多数实现中,它比StringBuffer要快
- 在StringBuilder上的主要操作是 append 和 insert 方法,可重载这些方法,以接受任意类型的数据
- StringBuilder 和 StringBuffer 均代表可变的字符序列,方法是一样的,所以使用和StringBuffer一样
package com.zanedu.stringbuilder_;
public class StringBuilder01 {
public static void main(String[] args) {
//解读
/*
1. StringBuilder 继承 AbstractStringBuilder 类
2. 实现了 Serializeable 说明 StringBuilder对象是可以串行化的(对象可以网络传输,可以保存文件)
3. StringBuilder 是final类,不能被继承
4. StringBuilder对象的字符序列仍然是存放在其父类AbstractStringBuilder 的 charp[] value
因此 字符序列存放在堆中
5. StringBuilder的方法,没有做互斥的处理,即没有synchronized关键字,因此在单线程的情况下使用StringBuilder
*/
StringBuilder stringBuilder = new StringBuilder();
}
}
String、StringBuffer、StringBuilder的比较
- StringBuilder 和 StringBuffer非常类似,均代表可变的字符序列,而且方法也一样
- String:不可变字符序列,效率低,但是复用率高
- StringBuffer:可变字符序列,效率较高(增删)、线程安全
- StringBuilder:可变字符序列,效率最高、线程不安全
- String使用注意说明:
String s = “a”;//创建了一个字符串
s += “b”;//实际上原来的"a"字符串对象已经丢弃了,现在又产生了一个字符串 s + “b”(也就 是"ab")。如果多次执行这些改变串内容的操作,会导致大量副本字符串对象存留在内存中,降低效 率。如果这样的操作放到循环中,会极大的影响程序的性能
结论:如果我们对String做大量修改,不要使用String
String、StringBuffer、StringBuilder的效率测试
- StringBuilder > StringBuffer > String
package com.zanedu.stringbuilder_;
public class StringVsStringBufferVsStringBuilder {
public static void main(String[] args) {
long startTime = 0L;
long endTime = 0L;
StringBuffer buffer = new StringBuffer("");
startTime = System.currentTimeMillis();
for (int i = 0; i < 80000; i++) {//StringBuffer 拼接 20000次
buffer.append(String.valueOf(i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuffer的执行时间:" + (endTime - startTime));
StringBuilder builder = new StringBuilder("");
startTime = System.currentTimeMillis();
for (int i = 0; i < 80000; i++) {//StringBuilder 拼接 20000次
builder.append(String.valueOf(i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuilder的执行时间:" + (endTime - startTime));
String text = "";
startTime = System.currentTimeMillis();
for (int i = 0; i < 80000; i++) {//String 拼接 20000
text = text + i;
}
endTime = System.currentTimeMillis();
System.out.println("String的执行时间:" + (endTime - startTime));
}
}
String、StringBuffer、StringBuilder的选择
使用的原则、结论:
- 如果字符串存在大量的修改操作,一般使用 StringBuffer 或 StringBuilder
- 如果字符串存在大量的修改操作,并在单线程的情况,使用 StringBuilder
- 如果字符串存在大量的修改操作,并在多线程的情况,使用 StringBuffer
- 如果我们字符串很少修改,被多个对象引用,使用 String,比如配置信息等
Math类
基本介绍
- Math类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数
方法一览(都为静态方法)
package com.zanedu.math_;
public class MathMethod {
public static void main(String[] args) {
//看看Math常用的方法(静态方法)
//1.abs 绝对值
int abs = Math.abs(-9);
System.out.println(abs);//9
//2.pow 求幂
double pow = Math.pow(2, 4);//2的4次方
System.out.println(pow);//16
//3.ceil 向上取整,返回>=该参数的最小整数(转成double);
double ceil = Math.ceil(3.9);
System.out.println(ceil);//4.0
//4.floor 向下取整,返回<=该参数的最大整数(转成double)
double floor = Math.floor(4.001);
System.out.println(floor);//4.0
//5.round 四舍五入 Math.floor(该参数+0.5)
long round = Math.round(5.51);
System.out.println(round);//6
//6.sqrt 求开方
double sqrt = Math.sqrt(9.0);
System.out.println(sqrt);//3.0
//7.random 求随机数
// random 返回的是 0 <= x < 1 之间的一个随机小数,左闭右开
// 思考:请写出获取 a-b之间的一个随机整数,a,b均为整数 ,比如 a = 2, b=7
// 即返回一个数 x 2 <= x <= 7
// 老韩解读 Math.random() * (b-a) 返回的就是 0 <= 数 <= b-a
// (1) (int)(a) <= x <= (int)(a + Math.random() * (b-a +1) )
// (2) 使用具体的数给小伙伴介绍 a = 2 b = 7
// (int)(a + Math.random() * (b-a +1) ) = (int)( 2 + Math.random()*6)
// Math.random()*6 返回的是 0 <= x < 6 小数
// 2 + Math.random()*6 返回的就是 2<= x < 8 小数
// (int)(2 + Math.random()*6) = 2 <= x <= 7
// (3) 公式就是 (int)(a + Math.random() * (b-a +1) )
for(int i = 0; i < 100; i++) {
System.out.println((int)(2 + Math.random() * (7 - 2 + 1)));
}
//max , min 返回最大值和最小值
int min = Math.min(1, 9);
int max = Math.max(45, 90);
System.out.println("min=" + min);
System.out.println("max=" + max);
}
}
Arrays类
Arrays类常见方法应用案例
- Arrays里面包含了一系列静态方法,用于管理或操作数组(比如排序和搜索)
- toString 返回数组的字符串形式
Arrays.toString(arr);
package com.zanedu.arrays_;
import java.util.Arrays;
import java.util.Comparator;
public class ArraysMethod01 {
public static void main(String[] args) {
Integer[] integers = {1, 20, 90};
//遍历数组
for (int i = 0; i < integers.length; i++) {
System.out.println(integers[i]);
}
//直接使用Arrays.toString方法,显示数组
System.out.println(Arrays.toString(integers));//[1, 20, 90]
}
- sort 排序(自然排序和定制排序)
package com.zanedu.arrays_;
import java.util.Arrays;
import java.util.Comparator;
public class ArraysSortCustom {
public static void main(String[] args) {
int[] arr = {1, -1, 8, 0, 20};
//bubble01(arr);
bubble02(arr, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
int i1 = (Integer)o1;//拆箱
int i2 = (Integer)o2;
return i1 - i2;//return i2 - i1
}
});
System.out.println("===定制排序后的情况===");
System.out.println(Arrays.toString(arr));
}
//使用冒泡完成排序
public static void bubble01(int[] arr) {
int temp = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
//从小到大
if (arr[i] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
//结合冒泡 + 定制
public static void bubble02(int[] arr, Comparator c) {
int temp = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
//数组的排序由c.compare(arr[j], arr[j + 1]返回的值决定
if (c.compare(arr[j], arr[j + 1]) > 0) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
package com.zanedu.arrays_;
import java.util.Arrays;
import java.util.Comparator;
public class ArraysMethod01 {
public static void main(String[] args) {
//演示sort方法的使用
Integer[] arr = {1, -1, 7, 9, 89};
//进行排序
//解读
//1. 可以直接使用冒泡排序,也可以直接使用Arrays提供的sort方法排序
//2. 因为数组是引用类型,所以通过sort排序后,会直接影响到实参arr
//3. sort重载的,也可以通过传入一个接口 Comparator 实现定制排序
//4. 这里调用定制排序时,传入了两个参数,(1)排序的数组arr
// (2)实现Comparator接口的匿名内部类,要求实现compare方法
//5. 先演示效果再解释
//6. 这里体现了接口编程的方式,看看源码
/*
源码分析
//(1) Arrays.sort(arr, new Comparator()
//(2) 最终到 TimSort类的 private static <T> void binarySort(T[] a, int lo, int hi, int start,
// Comparator<? super T> c)()
//(3) 执行到 binarySort方法的代码, 会根据动态绑定机制 c.compare()执行我们传入的
// 匿名内部类的 compare ()
// while (left < right) {
// int mid = (left + right) >>> 1;
// if (c.compare(pivot, a[mid]) < 0)
// right = mid;
// else
// left = mid + 1;
// }
//(4) new Comparator() {
// @Override
// public int compare(Object o1, Object o2) {
// Integer i1 = (Integer) o1;
// Integer i2 = (Integer) o2;
// return i2 - i1;
// }
// }
//(5) public int compare(Object o1, Object o2) 返回的值>0 还是 <0
// 会影响整个排序结果, 这就充分体现了 接口编程+动态绑定+匿名内部类的综合使用
// 将来的底层框架和源码的使用方式,会非常常见
*/
// 默认排序方法:
Arrays.sort(arr);
System.out.println("排序后");
System.out.println(Arrays.toString(arr));
//定制排序
Arrays.sort(arr, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Integer i1 = (Integer)o1;
Integer i2 = (Integer)o2;
// return i1 - i2;
return i2 - i1;
}
});
System.out.println("排序后");
System.out.println(Arrays.toString(arr));
}
}
- binarySearch 通过二分搜索法进行查找,前提是有序
package com.zanedu.arrays_;
import java.util.Arrays;
import java.util.List;
public class ArraysMethod02 {
public static void main(String[] args) {
Integer[] arr = {1, 2, 90, 123, 567};
//binarySearch 通过二分搜索法进行查找,要求必须排好
//解读
/*
1. 如果使用binarySearch 二叉查找
2. 要求该数组是有序的,如果该数组是无序的,不能使用binarySearch
3. 如果数组中不存在该元素,就返回 return -(low + 1); // key not found.
low代表应该存在的位置,如92应该在90-123之间,因此92的low就是3
*/
int index = Arrays.binarySearch(arr, 92);
System.out.println(index);
}
}
- copyOf 数组元素的复制
package com.zanedu.arrays_;
import java.util.Arrays;
import java.util.List;
public class ArraysMethod02 {
public static void main(String[] args) {
//copyOf 数组元素的赋值
//解读
/*
1. 从 arr数组中拷贝 arr.length个元素到 newArr数组中
2. 如果拷贝的长度 > arr.length,就在新数组的后面插入一个null
3. 如果拷贝的长度 < 0,就抛出异常 NegativeArraysSizeException
4. 该方法的底层使用的是 System.arraycopy()
*/
Integer[] arr = {1, 2, 90, 123, 567};
Integer[] newArr = Arrays.copyOf(arr, arr.length);
System.out.println("===拷贝执行完毕后===");
System.out.println(Arrays.toString(newArr));
}
- fill 数组元素的填充
package com.zanedu.arrays_;
import java.util.Arrays;
import java.util.List;
public class ArraysMethod02 {
public static void main(String[] args) {
//fill 数组元素的填充
Integer[] num = new Integer[]{9, 3, 2};
//解读
/*
1. 用后面指定的元素99 去填充num这个数组,可以理解成替换原来的元素(所有)
*/
Arrays.fill(num, 99);
System.out.println("===num数组填充后===");
System.out.println(Arrays.toString(num));
}
}
- equals 比较两个数组元素内容是否完全一致
package com.zanedu.arrays_;
import java.util.Arrays;
import java.util.List;
public class ArraysMethod02 {
public static void main(String[] args) {
//equals 比较两个数组元素内容是否完全一致
Integer[] arr = {1, 2, 90, 123, 567};
Integer[] arr2 = {1, 2, 90, 123};
//解读
/*
1. 如果arr 和 arr2 数组的元素一样,则返回true
2. 如果不是完全一样,就返回false
*/
boolean equals = Arrays.equals(arr, arr2);
System.out.println(equals);
}
}
- asList将一组值,转换成list
package com.zanedu.arrays_;
import java.util.Arrays;
import java.util.List;
public class ArraysMethod02 {
public static void main(String[] args) {
//asList 将一组值,转换成list
//解读
/*
1. asList方法, 会将(2, 3, 4, 5, 6, 1)数据转成一个List集合
2. 返回的asList 编译类型 List(接口)
3. 返回的asList 运行类型 java.util.Arrays$ArrayList,是Arrays类的静态内部类
private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable
*/
List asList = Arrays.asList(2, 3, 4, 5, 6, 1);
System.out.println(asList);
System.out.println("asList的运行类型=" + asList.getClass());
}
}
Arrays类课堂练习
案例:自定义Book类,里面包含name和price,按price排序(从大到小)。有一个Book[] books = 4本书对象
使用前面学习过的传递,实现Comparator接口匿名内部类,也称为定制排序
package com.zanedu.arrays_;
import java.util.Arrays;
import java.util.Comparator;
/**
* 案例:自定义Book类,里面包含name和price,按price排序(从大到小)。
* 要求使用两种方式排序 , 有一个 Book[] books = 4本书对象.
*
* 使用前面学习过的传递 实现Comparator接口匿名内部类,也称为定制排序。
* [同学们完成这个即可 10min ],
* 可以按照 price (1)从大到小 (2)从小到大 (3) 按照书名长度从大到小
*/
public class ArrayExercise {
public static void main(String[] args) {
Book[] books = new Book[4];
books[0] = new Book("红楼梦", 100);
books[1] = new Book("金瓶梅新", 90);
books[2] = new Book("青年文摘20年", 5);
books[3] = new Book("java从入门到放弃", 300);
//按照 price (1)从大到小
Arrays.sort(books, new Comparator<Book>() {
//这里是对books数组进行跑徐,因此o1 和 o2 要为Book对象
@Override
public int compare(Book o1, Book o2) {
Book book1 = (Book)o1;
Book book2 = (Book)o2;
double priceVal = book2.getPrice() - book1.getPrice();
//这里进行了一个转换
//如果发现结果和我们输出的不一致,就修改一下返回的 1 和 -1
if (priceVal > 0) {
return 1;
} else if (priceVal < 0) {
return -1;
} else {
return 0;
}
}
});
System.out.println(Arrays.toString(books));
//3. 按照书名长度从大到小排序
Arrays.sort(books, new Comparator<Book>() {
//这里是对books数组进行跑徐,因此o1 和 o2 要为Book对象
@Override
public int compare(Book o1, Book o2) {
Book book1 = (Book)o1;
Book book2 = (Book)o2;
//要求按照书名的长度来进行排序
return book2.getName().length() - book1.getName().length();
}
});
System.out.println(Arrays.toString(books));
}
}
class Book {
private String name;
private double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
System类
System类常见方法和案例
- exit:退出当前程序
package com.zanedu.system_;
import java.util.Arrays;
public class System_ {
public static void main(String[] args) {
//exit退出当前程序
System.out.println("ok1");
//解读
//1. exit(0)表示程序退出
//2. 0表示一个状态,表示正常的状态
System.exit(0);
System.out.println("ok2");
}
}
- arraycopy:复制数组元素,比较适合底层调用,一般使用Arrays.copyOf完成复制数组
package com.zanedu.system_;
import java.util.Arrays;
public class System_ {
public static void main(String[] args) {
//arraycopy:赋值数组元素,比较适合底层调用
//一般使用Arrays.copyOf完成复制数组
int[] src = {1, 2, 3};
int[] dest = new int[3];//dest 当前是 {0, 0, 0}
//解读
/*
1. 主要是搞清楚这5个参数的含义
* @param src the source array. 源数组
* @param srcPos starting position in the source array. 从源数组的哪一个索引位置开始拷贝
* @param dest the destination array. 目标数组,即把源数组的数据拷贝到哪个数组
* @param destPos starting position in the destination data. 把源数组的数据拷贝到目标数组的哪个索引
* @param length the number of array elements to be copied. 从源数组拷贝多少个数据到目标数组
*/
//这里有范围问题
// System.arraycopy(src, 0, dest, 0, src.length);//一般是这样子写的
System.arraycopy(src, 1, dest, 1, 2);
System.out.println(Arrays.toString(dest));
}
}
- currentTimeMillens:返回当前时间距离 1970-1-1的毫秒数
package com.zanedu.system_;
import java.util.Arrays;
public class System_ {
public static void main(String[] args) {
//currentTimeMillens:返回当前时间距离1970-1-1的毫秒数
System.out.println(System.currentTimeMillis());
}
}
- gc:运行垃圾回收机制 System.gc();
BigInteger 和 BigDecimal类
基本介绍
应用场景:
- BigInteger适合保存比较大的整型
- BigDecimal适合保存精度更高的浮点型(小数)
BigInteger 和 BigDecimal 常见方法
- add 加
- subtract 减
- multiply 乘
- divide 除
package com.zanedu.bignum;
import java.math.BigInteger;
public class BigInteger_ {
public static void main(String[] args) {
//当我们编程中,需要处理很大的整数,long就不够用了
//可以使用BigInteger的类来搞定
// long l = 2348888888123l;
// System.out.println(l);
BigInteger bigInteger = new BigInteger("123123123919239123123123213121");
BigInteger bigInteger1 = new BigInteger("100");
System.out.println(bigInteger);
//解读
/*
1. 在BigInteger 进行加减乘除的时候,需要使用对应的方法,不能直接进行 + - * /
2. 可以创建一个要操作的 BigInteger,然后进行相应操作
*/
// System.out.println(bigInteger + 1);
BigInteger add = bigInteger.add(bigInteger1);
System.out.println(add);//加法
BigInteger sub = bigInteger.subtract(bigInteger1);
System.out.println(sub);//减法
BigInteger multiply = bigInteger.multiply(bigInteger1);
System.out.println(multiply);//乘法
BigInteger divide = bigInteger.divide(bigInteger1);
System.out.println(divide);//除法
}
}
package com.zanedu.bignum;
import java.math.BigDecimal;
public class BigDecimal_ {
public static void main(String[] args) {
//当我们需要保存精度很高的数时,double不够用了
//可以使用BigDecimal
// double d = 1.231313212321132311231213121231d;
// System.out.println(d);
BigDecimal bigDecimal = new BigDecimal("123.2311312312339123312123157");
System.out.println(bigDecimal);
//解读:
/*
1. 如果对BigDecimal进行运算,比如加减乘除,需要使用对应的方法
2. 创建一个需要操作的 BigDecimal,然后调用相应的方法即可
*/
// System.out.println(bigDecimal + 1);//error
BigDecimal bigDecimal1 = new BigDecimal("12.2133132");
System.out.println(bigDecimal.add(bigDecimal1));
System.out.println(bigDecimal.subtract(bigDecimal1));
System.out.println(bigDecimal.multiply(bigDecimal1));
// System.out.println(bigDecimal.divide(bigDecimal1));//可能会抛出异常,有可能除不尽 ArithmeticException
//在调用divide方法时,指定精度即可,BigDecimal.ROUND_CEILING
//如果有无限循环小数,就会保留分子的精度
System.out.println(bigDecimal.divide(bigDecimal1, BigDecimal.ROUND_CEILING));
}
}
日期类
第一代日期类
- Date:精确到毫秒,代表特定的瞬间
- SimpleDateFormat:格式和解析日期的类,它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化
package com.zanedu.date_;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Date01 {
public static void main(String[] args) throws ParseException {
//解读
//1. 获取当前系统时间
//2. 这里的Date 类是在java.util包,不是数据库里面的包
//3. 默认输出的日期格式是国外的方式, 因此通常需要对格式进行转换
Date d1 = new Date(); //获取当前系统时间
System.out.println("当前日期=" + d1);
Date d2 = new Date(9234567); //通过指定毫秒数得到时间
System.out.println("d2=" + d2); //获取某个时间对应的毫秒数
//
//解读
//1. 创建 SimpleDateFormat对象,可以指定相应的格式
//2. 这里的格式使用的字母是规定好,不能乱写
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss E");
String format = sdf.format(d1); // format:将日期转换成指定格式的字符串
System.out.println("当前日期=" + format);
//解读
//1. 可以把一个格式化的String 转成对应的 Date
//2. 得到Date 仍然在输出时,还是按照国外的形式,如果希望指定格式输出,需要转换
//3. 在把String -> Date , 使用的 sdf 格式需要和你给的String的格式一样,否则会抛出转换异常
String s = "1996年01月01日 10:20:30 星期一";
Date parse = sdf.parse(s);
System.out.println("parse=" + sdf.format(parse));
}
}
第二代日期类
- 第二代日期类,主要就是 Calendar类(日历)
public abstract class Calendar extends Object implements Serializable**,** Cloneable**,** Comparable
- Calendar类是一个抽象类,它为特定瞬间与一组诸如 YEAR、MONTH、DAT_OF_MONTH、HOUR等日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法
package com.zanedu.date_;
import java.util.Calendar;
public class Calendar_ {
public static void main(String[] args) {
// Calendar
/*
解读
1. Calendar 是一个抽象类,并且构造器是private,无法new
2. 可以通过getInstance() 来获取实例
3. 提供了大量的方法和字段
4. Calendar没有提供对于的格式化的类,因此需要程序员自己组合来输出(灵活)
5. 如果我们需要按照24小时进制来获取小时数,Calendar.HOUR ==改成== Calendar.HOUR_OF_DAY
*/
// new Calendar();//error 抽象类无法new
Calendar c = Calendar.getInstance(); //创建日历类对象//比较简单,自由
System.out.println("c=" + c);
//2.获取日历对象的某个日历字段
System.out.println("年:" + c.get(Calendar.YEAR));
// 这里为什么要 + 1, 因为Calendar 返回月时候,是按照 0 开始编号
System.out.println("月:" + (c.get(Calendar.MONTH) + 1));
System.out.println("日:" + c.get(Calendar.DAY_OF_MONTH));
System.out.println("小时:" + c.get(Calendar.HOUR));
System.out.println("分钟:" + c.get(Calendar.MINUTE));
System.out.println("秒:" + c.get(Calendar.SECOND));
//Calender 没有专门的格式化方法,所以需要程序员自己来组合显示
System.out.println(c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH) +
" " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND) );
}
}
第三代日期类
- 前面两代日期类的****不足分析
JDK1.0中包含了一个java,util.Date类,但是它的大多数方法已经在JDK1.1引入Calendar类之后被弃用了。
而Calendaar也存在问题是:
- 可变性:像日期和时间这样的类应该是不可变的
- 偏移性:Date中的年份是从1900开始的,而月份都从0开始
- **格式化:格式化只对Date有用,Calendar则不行,**Calendar没有提供对于的格式化的类
- 此外,它们也不是线程安全的;不能处理闰秒等(每隔2天,多出1s)
LocalDate(日期/年月日)、LocatTime(时间/时分秒)、LocalDateTime(日期时间/年月日时分秒)
注意:JDK8才加入这些方法
LocalDate只包含日期,可以获取日期字段
LocalTime只包含时间,可以获取时间字段
LocalDateTime包含日期+时间,可以获取日期和时间字段
package com.zanedu.date_;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class LocalDate_ {
public static void main(String[] args) {
//第三代日期
/*
解读
1. 使用 now() 返回表示当前日期时间的对象
*/
LocalDateTime ldt = LocalDateTime.now(); //LocalDate.now();//LocalTime.now()
System.out.println(ldt);
System.out.println("年=" + ldt.getYear());
System.out.println("月=" + ldt.getMonth());//英文的月份
System.out.println("月=" + ldt.getMonthValue());//数字的月份
System.out.println("日=" + ldt.getDayOfMonth());
System.out.println("时=" + ldt.getHour());
System.out.println("分=" + ldt.getMinute());
System.out.println("秒=" + ldt.getSecond());
LocalDate now = LocalDate.now();//可以获取年月日
System.out.println(now);
LocalTime now2 = LocalTime.now();//可以获得时分秒
System.out.println(now2);
}
}
DateTimeFormatter格式日期类
- 类似于SimpleDateFormat
DateTimeFormat dtf = DateTimeFormatter.ofPattern(格式);
String str - dtf.format(日期对象);
package com.zanedu.date_;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class LocalDate_ {
public static void main(String[] args) {
//第三代日期
/*
解读
1. 使用 now() 返回表示当前日期时间的对象
*/
LocalDateTime ldt = LocalDateTime.now(); //LocalDate.now();//LocalTime.now()
System.out.println(ldt);
//2. 使用DateTimeFormatter进行格式化
//创建 DateTimeFormatter对象
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH小时mm分钟s秒");
String format = dtf.format(ldt);
System.out.println("格式化的日期=" + format);
System.out.println("年=" + ldt.getYear());
System.out.println("月=" + ldt.getMonth());//英文的月份
System.out.println("月=" + ldt.getMonthValue());//数字的月份
System.out.println("日=" + ldt.getDayOfMonth());
System.out.println("时=" + ldt.getHour());
System.out.println("分=" + ldt.getMinute());
System.out.println("秒=" + ldt.getSecond());
LocalDate now = LocalDate.now();//可以获取年月日
System.out.println(now);
LocalTime now2 = LocalTime.now();//可以获得时分秒
System.out.println(now2);
}
}
Instant时间戳
类似于Date,提供了一系列和Date类转换的方式
Instant --> Date:Date date = Date.from(instant);
Date --> Instant:Instant instant = date.toInstant();
package com.zanedu.date_;
import java.time.Instant;
import java.util.Date;
public class Instant_ {
public static void main(String[] args) {
//1. 通过静态方法now() 获取表示当前时间戳的对象
Instant now = Instant.now();
System.out.println(now);
//2. 通过 from 可以把 Instant转成 Date
Date date = Date.from(now);
//3. 通过date的 toInstant() 可以把date转成Instant对象
Instant instant = date.toInstant();
}
}
第三代日期类更多方法
LocalDateTime类
MonthDay类:检查重复事件
使用plus方法测试增加时间的某个部分
使用minus方法测试查看一年前和一年后的日期
其他的方法,查看API即可
package com.zanedu.date_;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class LocalDate_ {
public static void main(String[] args) {
LocalDateTime ldt = LocalDateTime.now(); //LocalDate.now();//LocalTime.now()
System.out.println(ldt);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH小时mm分钟s秒");
String format = dtf.format(ldt);
System.out.println("格式化的日期=" + format);
//提供 plus 和 minus方法可以对当前时间进行加或者减
//看看 890天后,是什么时候,把年月日时分秒输出
LocalDateTime localDateTime = ldt.plusDays(890);
System.out.println("890天后=" + dtf.format(localDateTime));
//看看在 3456分钟前是什么时候,把年月日时分秒输出
LocalDateTime localDateTime1 = ldt.minusMinutes(3456);
System.out.println("3456分钟前 日期是=" + dtf.format(localDateTime1));
}
}
练习题
题一
编程题:
- 将字符串中指定部分进行翻转。比如将"abcdef"反转为"aedcbf"
- 编写方法 public static String reverse(String str, int start, int end)
package com.zanedu.homework;
public class Homework01 {
public static void main(String[] args) {
String str = "abcdef";
System.out.println("===交换前===");
System.out.println(str);
try {
str = reverse(str, 1, 4);
} catch (Exception e) {
System.out.println(e.getMessage());
return;
}
System.out.println("===交换后===");
System.out.println(str);
}
public static String reverse(String str, int start, int end) {
//对输入的参数做一个验证
//重要的编程技巧!!!
//(1)先写出正确的情况
//(2)然后取反即可 ==> 不正确的情况
if (!(str != null && start >= 0 && end > start && end < str.length())) {
throw new RuntimeException("参数不正确");
}
//将字符串转换成字符数组
char[] chars = str.toCharArray();
while (start < end) {
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
start++;
end--;
}
//使用chars 重新构建一个 String返回即可
return new String(chars);
}
}
/**
* (1) 将字符串中指定部分进行反转。比如将"abcdef"反转为"aedcbf"
* (2) 编写方法 public static String reverse(String str, int start , int end) 搞定
* 思路分析
* (1) 先把方法定义确定
* (2) 把 String 转成 char[] ,因为char[] 的元素是可以交换的
*/
题二
编程题:
输入用户名、密码、邮箱,如果信息录入正确,则提示注册成功,否则生成异常对象
要求:
- 用户名长度为2或3或4
- 密码的长度为6,要求全是数字(编写方法isDigital)
- 邮箱中包含@和. 并且 @ 在 . 的前面
package com.zanedu.homework;
public class Homework02 {
public static void main(String[] args) {
String name = "zan";
String pwd = "123112";
String email = "213@qq.com";
try {
userRegister(name, pwd, email);
System.out.println("恭喜你注册成功");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void userRegister(String name, String pwd, String email) {
//可以再加入一些校验
if (!(name != null && pwd != null && email != null)) {
throw new RuntimeException("参数不能为空");
}
//过关
//1. 校验名字
int userLength = name.length();
if (!(userLength >= 2 && userLength <= 4)) {
throw new RuntimeException("用户名长度应为2或3或4");
}
//2. 校验密码
if (!(pwd.length() == 6 && isDigital(pwd))) {
throw new RuntimeException("密码长度为6,并且要求全是数字");
}
//3. 校验邮箱
int i = email.indexOf('@');
int j = email.indexOf('.');
if (!(i > 0 && i < j)) {
throw new RuntimeException("邮箱中包含@和. 并且@在.的前面");
}
}
//单独的写一个方法,判断 密码是否全部是数字字符 boolean
public static boolean isDigital(String str) {
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] < '0' || chars[i] > '9') {
//不是数字
return false;
}
}
return true;
}
}
/**
* 输入用户名、密码、邮箱,如果信息录入正确,则提示注册成功,否则生成异常对象
* 要求:
* (1) 用户名长度为2或3或4
* (2) 密码的长度为6,要求全是数字 isDigital
* (3) 邮箱中包含@和. 并且@在.的前面
* <p>
* 思路分析
* (1) 先编写方法 userRegister(String name, String pwd, String email) {}
* (2) 针对 输入的内容进行校核,如果发现有问题,就抛出异常,给出提示
* (3) 单独的写一个方法,判断 密码是否全部是数字字符 boolean
*/
题三
编程题:
- 编写java程序,输入形式为:Han Shun Ping的人名,以Ping,Han.S的形式打印出来。其中.S是中间单词的首字母
- 例如输入"Willian Jefferson Clinton",输出格式为:Clinton,Willian.J
package com.zanedu.homework;
public class Homework03 {
public static void main(String[] args) {
String str = "Han shun Ping";
printName(str);
String str2 = "Willian Jefferson Clinton";
printName(str2);
}
public static void printName(String str) {
if (str == null) {
System.out.println("str不能为空");
return;
}
String[] strNew = str.split(" ");
if (strNew.length != 3) {
System.out.println("输入的字符串格式不对");
return;
}
String format = String.format("%s,%s.%s", strNew[2], strNew[0], strNew[1].toUpperCase().charAt(0));
System.out.println(format);
}
}
/**
* 编写方法: 完成输出格式要求的字符串
* 编写java程序,输入形式为: Han shun Ping的人名,以Ping,Han .S的形式打印出来,其中.S是中间单词的首字母
* 思路分析
* (1) 对输入的字符串进行 分割split(" ")
* (2) 对得到的String[] 进行格式化String.format()
* (3) 对输入的字符串进行校验即可
*/
题四
需求:输入字符串,判断里面有多少个大写字母、多少个小写字母、多少个数字
package com.zanedu.homework;
public class Homework04 {
public static void main(String[] args) {
String str = "sad123u1jdsaSdad";
countStr(str);
}
public static void countStr(String str) {
if (str == null) {
System.out.println("输入不能为null");
return;
}
int numCount = 0;
int lowerCount = 0;
int upperCount = 0;
int otherCount = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
numCount++;
} else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
lowerCount++;
} else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
upperCount++;
} else {
otherCount++;
}
}
System.out.println(numCount);
System.out.println(lowerCount);
System.out.println(upperCount);
System.out.println(otherCount);
}
/**
* 判断一个字符串里面有多少个大写字母,有多少个小写字母,有多少个数字
* 分析:
* (1)遍历字符串,如果char 在 '0' - '9' 就是一个数字
* (2)'a' - 'z'
* (3)'A' - 'Z'
* 使用三个变量来存储
*/
}
题五
- 判断一下程序的输出是什么?
package com.zanedu.homework;
public class Homework05 {
public static void main(String[] args) {
String s1 = "hspedu";
Animal a = new Animal(s1);
Animal b = new Animal(s1);
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(a.name == b.name);
String s4 = new String("hspedu");
String s5 = "hspedu";
System.out.println(s1 == s4);
System.out.println(s4 == s5);
String t1 = "hello" + s1;
String t2 = "hellohspedu";
System.out.println(t1.intern() == t2);
}
}
class Animal {
String name;
public Animal(String name) {
this.name = name;
}
}