11常用类
目录
包装类
1.针对巴中基本数据类型相应的引用类型-包装类
2.有了类的特点,就可以调用类中的方法

包装类和基本数据的转换:
包装类和基本数据类型的互相转换,以int 和 Integer演示

测试题:
1下面的代码是否正确
Doubled d = 100d;//ok,自动装箱Double.valueOf(100d);
Float f = 1.5f;ok,自动装箱 Float.valueOf(1.5f);
2下面两个题目输出结果相同吗,分别是什么。
Object obj1 = true? new Integer(1):new Double(2.0);
//三元运算符[是一个整体]
System.out.println(obj1);//1.0
object obj2;
if(true){
obj2 = new Integer(1);
}else{
obj2 = new Double(2.0);
}System.out.println(obj2);//1,分别计算
包装类型和String类型的相互转换

Integer类和Character类的常用方法
System.out.println(Integer.MIN_VALUE);//返回最小值
System.out.println(Integer.MAX_VALUE);//返回最大值
System.out.println(Character.isDigit('i'));//判断是不是数字
System.out.println(Character.isLetter('i'));//判断是不是字母
System.out.println(Character.isUpperCase('i'));//判断是不是大写
System.out.println(Character.isLowerCase('i'));//判断是不是小写
System.out.println(Character.isWhitespace('i'));//判断是不是空格
System.out.println(Character.toUpperCase('i'));//转成大写
System.out.println(Character.toLowerCase('I'));//转成小写
:练习题
1看看下面输出什么结果
public void method1(){
Integer i = new Integer(1);
Integer j = new Integer(1);
System.out.println(i == j)//F,对象比较看地址
Integer m = 1;//底层 Integer.valueOf(1);
Integer n = 1;底层 Integer.valueOf(1);
System.out.println(m == n);//T
//这里主要是看范围-128~127就是直接返回,不然就new一个对象
//如果X在IntegerCache.low(-128)~IntegerCache.low(127).直接从数组返回
//如果不在-128~127,就直接new Integer(x);
Integer x = 128;
Integer y = 128;
System.out.println(x == y);//F
}
2 看看下面输出什么
示例一
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 i6 = 127;
System.out.println(i5 == i6);//T
示例四
Integer i7 = 128;
Integer i8 = 128;
System.out.println(i7 == i8);//F
示例五
Integer i9 = 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 = new Integer(128);
System.out.println(i13 == i14);//T
String类
1.String 对象用于保存字符串,也就是一组字符序列
2.字符串常量对象时用双引号括起的字符序列。如:"你好","hello"
3.字符串的字符使用Unicode字符编码,一个字符(不区分字符还是汉字)栈两个字节
4.String类比较常用的构造方法:
String s1 = new String();
String s2 = new String(SString original);
String s3 = new String(char[] a);
String s4 = new String(char[] a,int startIndex,int count);
创建String对象的两种方式:
1.方式一:直接赋值 String s = "hsp";
2.方式二:调用构造器 String s = new String("hsp");
两种创建String对象的区别:
1.方式一:先从常量池查看是否有"HSP"数据空间,如果有,直接指向;如果没有则重写创建,然后指向。s最终指向的是常量池的空间地址
2.方式二:现在堆中创建空间,里面维护了value属性,指向常量池的hsp空间。如果常量池没有"hsp",重写创建,如果有,直接通过value指向。最终指向的是堆中的空间地址。

练习
1测试题:
String a = "abc";
String b = "abc";
System.out.println(a.equals(b));//T,比较内容
System.out.println(a == b);//T
2测试题:
String a = new String("abc");
String b = new String("abc");
System.out.println(a.equals(b));//T
System.out.println(a==b);//F
3测试题:
String a = "hsp";//a指向常量池的 "hsp"
String b = new String("hsp");//b指向堆中的对象
System.out.println(a.equals(b));//T
System.out.println(a == b);//F
System.out.println(a == b.intern());//T
//当调用intern方法时,如果池已经包含一个等于此String对象的字符串(用equals(Object)方法确定),则返回池中的字符串.否则将次String对象添加到池中,并返回此String对象的引用.解读:1b.intern()方法最终返回的是常量池的地址(对象)
System.out.println(b == b.intern());//F
4测试题:
String s1 = "hsp";//指向常量池hsp
String s2 = "java";//指向常量池java
String s3 = "java";//指向常量池java
String s4 = new String("java");//指向堆中对象
System.out.println(s2 == s4);//F
System.out.println(s2 == s3);//T
System.out.println(s2.equals(s4));//T
System.out.println(s1 == s2);//F
5测试题:
Person p1 = new Person();
p1.name = "hsp";
Person p2 = new Person();
p2.name = "hspedu";
System.out.println(p1.name.equals(p2.name));//T
System.out.println(p1.name == p2.name);//T
System.out.println(p1.name == "hspedu");//T
String s1 = new String("bcde");
String s2 = new String("bcde");
System.out,println(s1 == s2);//F
String的特性
1.String 是一个final 类,代表不可变的字符序列
2.字符串是不可变的。一个字符串对象一般被分配,其内容是不可变的。
练习:
1.以下语句创建了几个对象?
String s1 = "hello";
s1 = "haha";//两个对象
2.创建了几个对象:
String a = "hello"+"abc";//一个对象
//解读"hello"+"abc";→优化 等价于String a="helloabc";
//判断创建的常量池对象,是否有引用指向
//String a= "hello"+"abc";→ String a = "helloabc";
3.创建了几个对象:
String a = "hello";//创建a对象
String b = "abc";创建b对象
//1.先创建一个 StringBuilder sb = StringBuilder();
//2.执行 sb.append("hello");
//3.sb.append("abc");
//4.String s = sb.toString
//最后其实是c指向堆中的对象(String) value[] → 池中 "helloabc"
String c = a+b;//三个对象
String d = "helloabc";
System.out.println(c == d);//F
/*小结:底层是StringBuilder sb = new StringBuilder(); sb.append(a);
sb.append(b);sb是在堆中,并且append是在原理字符串的基础上追加的。
重要规则:
String c1 = "ab" + "cd";常量相加,看的是池。
String c1 = a + b;变量相加,是在堆中*/
4下面输出什么:
String s1 = "hspedu";//s1指向池中 "hspedu"
String s2 = "java";//s2指向池中的 "java"
String s3 = "hspedujava";//s3 指向池中的"hspedujava"
String s4 = (s1+s2).intern();//s4 指向池中的 "hspedujava"
System.out.println(s3==s4);//T
System.out.println(s3.equals(s4));//T
5下列运行结果是什么:
public class Test1{
String str = new String("hsp");
final char[] ch = {'j','a','v','a'};
public void change(String str, char ch[]){
str = "java"
ch0 = 'h';
}
public static void main(String[] args){
Test1 ex = new Test1();
ex.change(ex.str,ex.ch);
System.out.println(ex.str+"and");//hspand
System.out.println(ex.ch);//hava
}
}
String类的常见方法
String类是保存字符串常量的。每次更新都需要重新开辟空间,效率较低,因此java设计者还提供了StringBuilder和StringBuffer来增强String的功能,并提高效率。
点击查看代码
String str1 = " hello ";
String str2 = " Hello ";
// 1.equals 区分大小写,判断内容是否相等
System.out.println(str1.equals(str2));//F
// 2.equalsIgnoreCase 忽略大小写的判断内容是否相等
System.out.println(str1.equalsIgnoreCase(str2));//T
// 3.length 获取字符的个数,字符串的长度
System.out.println(str1.length());//7
// 4.indexOf 获取字符在字符串中第一次出现的索引,索引从0开始,如果找不到,返回-1
System.out.println(str1.indexOf('l'));//3
System.out.println(str1.indexOf("he"));
// 5.lastIndexOf 获取字符在字符串中最后一次出现的索引,索引从0开始,如果找不到,返回-1
System.out.println(str1.lastIndexOf('l'));//4
// 6.substring 截取指定范围的子字符串
System.out.println(str1.substring(2));//ello 从索引2开始截取后面的字符
System.out.println(str1.substring(0,4));// hel表示从索引0开始截取,截取到索引4-1位置上
// 7.trim 去前后空格
System.out.println(str1.trim());//hello
// 8.charAt 获取某索引处的字符,注意不能使用Str[index]这种方式
System.out.println(str1.charAt(2));
String s = "hEllo";
String s1 = "hello";
String s = "hEllo";
String s1 = "hello";
// 9.toUpperCase 转换成大写
System.out.println(s.toUpperCase());
// 10.toLowerCase 转换成小写
System.out.println(s.toLowerCase());
// 11.concat 拼接字符串
System.out.println(s.concat("java").concat("真棒"));
// 12.replace 替换字符串中的字符
System.out.println(s.replace("l", "a"));
// 13.split 分隔字符串,对于某些分隔符,我们需要 转义比如|\\等
String[] ss = s.split("l");
for (int i = 0; i < ss.length; i++) {
System.out.println(ss[i]);
}
// 14.toCharArray 转成字符串数组
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
System.out.print(c[i] + " ");
}
System.out.println();
// 15.compareTo 比较两个字符串的大小,如果前者大则返回正数,后者大返回负数,相等返回0
System.out.println(s1.compareTo(s));
// 16.format 格式字符串 占位符有:%s 字符串 %c 字符 %d 整型 %.2f 浮点型
/* 1.%s %d %.2f %c称为占位符
2.这些占位符有后面变量来替换
3.%s表示由后面字符串替换
4.%d是整数来替换
5.%.2f表示用小数来替换,替换后,只会保留小数点两位,并且镜像四舍五入的处理
6.%c使用char类型来替换
*/
String name = "jack";
int age = 20;
double score = 56.88;
char sex = '男';
System.out.println(String.format("我的姓名%s我的年龄%d我的分数%.2f我的性别%c",name,age,score,sex));;
StringBuffer类
java.lang.StringBuffer代表可变的字符序列,可以对字符串内容进行增删。很多方法与String相同,但StringBuffer是可变长度的。StringBuffer是一个容器
1.StringBuffer直接父类 是 AbstractStringBuilder
2.StringBuffer 实现了 Serializable,即 StringBuffer的对象可以串行化
3.在父类中 AbstractStringBuilder 有属性 char[] value,不是final
该value 数组存放 字符串内容,因此存放在堆中
4.StringBuffer 是一个final类,不能被继承
5.因为StringBuffer 字符内容时存在 char[] value,所以在变化(增加/删除)不用每次都更换地址(即创不是每次建新对象),所以效率高于 String
String VS StringBuffer
1.String 保存的是字符串常量,里面的值不能更改,每次String类的更新实际上就是更改地址,效率较低//private final char value[];
2.StringBuffer 保存的是字符串变量,里面的值可以更改,每次StringBuffer的更新实际上可以更新内容,不用每次更新地址,效率较//char[] value; //放在堆
String和StringBuffer相互转换
点击查看代码
//String → StringBuffer
String str = "hello";
//方法一:使用构造器,返回的才是 StringBuffer 对象,对str本身没有影响
StringBuffer stringBuffer = new StringBuffer(str);
//方式二:使用的是 append 方法
StringBuffer stringBuffer1 = new StringBuffer();
stringBuffer1 = stringBuffer1.append(str);
//StringBuffer → String
StringBuffer hello = new StringBuffer("你好java");
//方式一:使用StringBuffer提供的toString方法
String s = hello.toString();
//方式二:使用构造器来搞定
String s1 = new String(hello);
练习:
1.看下面的代码输出什么
String str = nul;;
StringBuffer sb = new StringBuffer();
sb.append(Str);//底层调用的是 AbstractStringBuilder 的 appendNull
System.out.println(sb.length());//4
System.out.println(sb);//null
//下面构造器直接抛出空指针异常NullpointerException
StringBuffer sb1= newStringBuffer(Str);//null对象 str.length()+16
System.out.println(sb1);
2输入上面名称和商品价格,要求打印效果示例,使用前面学习的方法完成:
商品名 商品价格
手机 123,564.59
要求:几个的小数点前面没三围用逗号隔开
点击查看代码
StringBuilder类
1一个可变的字符序列。此类提供一个与StringBuffer兼容的API,但不保证同步。该类被设计用作StringBuffer的一个简易替换,用在字符串缓冲区被单个线程使用的时候。如果可能,简易优先采用该类,因为在大多数实现中,它比StringBuffer要快
2在StringBuilder 上的主要操作是append和insert方法,可重载这些方法,以接受仍以类型的数据
StringBuilder常用方法
StringBuilder 和 StringBuffer 均代表可变的字符序列,方法是一样的,索引使用和StringBuffer一样。
String、StringBuffer和StringBuilder的比较
1.StringBuffer 和 StringBuilder 非常类似,均代表可变的字符序列,而且方法也一样。
2.String:不可变字符序列,效率低,但是复用率高。
3.StringBuffer:可变字符序列、效率增高(增删)、线程安全
4.StringBuilder:可变字符序列、效率最高、线程不安全
5.String使用注意说明:
String s = "a";//创建了一个字符串
s += "b";//实际上原来的"a"字符串对象已经丢弃了,现在又产生了一个字符串s+"b"(也就是"ab")。如果多次执行这些改变串内容的操作,会导致大量副本字符串对象存留在内存中,降低效率。如果这样的操作放到循环中,会极大影响程序的性能。
结论:如果我们对String做大量修改,不要使用String
String、StringBuffer和StringBuilder的选择
1.如果字符串存在大量的修改操作,一般使用StringBuffer 或 StringBuilder
2.如果字符串存在大量的修改操作,并在单线程的情况,使用 StringBuilder
3.如果字符串存在大量的修改操作,并在多线程的情况,使用 StringBuffer
4.如果我们字符串很少修改,被多个对象引用,使用String,比如配置信息等
点击查看代码
//增加 append
StringBuffer s = new StringBuffer("hello");
s.append(",");
s.append("栗子");
s.append("今天").append("吃栗子");
System.out.println(s);
//删除 delete 删除索引为>=start && end 处的字符
//解读:删除1~3的字符[1,3]
s.delete(1,3);
System.out.println(s);
//改
s.replace(4,6,"小沈");
System.out.println(s);
//查找 indexOf 查找指定的子字符串在字符串第一次出现的所有,如果找不到返回-1
System.out.println(s.indexOf("小沈"));
//插 insert
//解读:在索引为9的位置插入":",原来索引为9的内容自动后移
s.insert(9,":");
System.out.println(s);
//长度
System.out.println(s.length());
Math类
Math类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数
点击查看代码
//1.abd 绝对值
int abs = Math.abs(-3);
System.out.println(abs);//3
//2.pow 求幂
double pow = Math.pow(2,3);//2的三次方
System.out.println(pow);//8.0
//3.ceil 向上取整数,返回>=该参数的最小整数
double ceil = Math.ceil(3.1);
System.out.println(ceil);//4.0
//4.floor 向下取整数,返回<=改参数的最大整数
double floor = Math.floor(2.9);
System.out.println(floor);//2.0
//5.round 四舍五入 Math.floor(该参数+0.5);
long round = Math.round(3.6);
System.out.println(round);//4
//6.sqrt 求开发
double sqrt = Math.sqrt(9.0);
System.out.println(sqrt);//3.0
//7.random 求随机数
/* random 返回的是0<=X<1 之间的一个随机小数 a=2,b=7
写出获取a-b之间的一个随机整数,a,b均为整数?
1.(int)(a) <= x < (int)(a+Math.random() *(b-a+1)
2.(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*/
int a=2;
int b=7;
for (int i = 0; i < 100; i++) {
int c = (int)(a+Math.random()*(b-a+1));
System.out.print(c+" ");
}
System.out.println();
//8.max,min返回最大值和最小值
int min = Math.min(1,6);
int max = Math.max(2,7);
System.out.println("min="+min);
System.out.println("max="+max);
//1.abd 绝对值
int abs = Math.abs(-3);
System.out.println(abs);//3
//2.pow 求幂
double pow = Math.pow(2,3);//2的三次方
System.out.println(pow);//8.0
//3.ceil 向上取整数,返回>=该参数的最小整数
double ceil = Math.ceil(3.1);
System.out.println(ceil);//4.0
//4.floor 向下取整数,返回<=改参数的最大整数
double floor = Math.floor(2.9);
System.out.println(floor);//2.0
//5.round 四舍五入 Math.floor(该参数+0.5);
long round = Math.round(3.6);
System.out.println(round);//4
//6.sqrt 求开发
double sqrt = Math.sqrt(9.0);
System.out.println(sqrt);//3.0
//7.random 求随机数
/* random 返回的是0<=X<1 之间的一个随机小数 a=2,b=7
写出获取a-b之间的一个随机整数,a,b均为整数?
1.(int)(a) <= x < (int)(a+Math.random() *(b-a+1)
2.(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*/
int a=2;
int b=7;
for (int i = 0; i < 100; i++) {
int c = (int)(a+Math.random()*(b-a+1));
System.out.print(c+" ");
}
System.out.println();
//8.max,min返回最大值和最小值
int min = Math.min(1,6);
int max = Math.max(2,7);
System.out.println("min="+min);
System.out.println("max="+max);
//1.abd 绝对值
int abs = Math.abs(-3);
System.out.println(abs);//3
//2.pow 求幂
double pow = Math.pow(2,3);//2的三次方
System.out.println(pow);//8.0
//3.ceil 向上取整数,返回>=该参数的最小整数
double ceil = Math.ceil(3.1);
System.out.println(ceil);//4.0
//4.floor 向下取整数,返回<=改参数的最大整数
double floor = Math.floor(2.9);
System.out.println(floor);//2.0
//5.round 四舍五入 Math.floor(该参数+0.5);
long round = Math.round(3.6);
System.out.println(round);//4
//6.sqrt 求开发
double sqrt = Math.sqrt(9.0);
System.out.println(sqrt);//3.0
//7.random 求随机数
/* random 返回的是0<=X<1 之间的一个随机小数 a=2,b=7
写出获取a-b之间的一个随机整数,a,b均为整数?
1.(int)(a) <= x < (int)(a+Math.random() *(b-a+1)
2.(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*/
int a=2;
int b=7;
for (int i = 0; i < 100; i++) {
int c = (int)(a+Math.random()*(b-a+1));
System.out.print(c+" ");
}
System.out.println();
//8.max,min返回最大值和最小值
int min = Math.min(1,6);
int max = Math.max(2,7);
System.out.println("min="+min);
System.out.println("max="+max);
//1.abd 绝对值
int abs = Math.abs(-3);
System.out.println(abs);//3
//2.pow 求幂
double pow = Math.pow(2,3);//2的三次方
System.out.println(pow);//8.0
//3.ceil 向上取整数,返回>=该参数的最小整数
double ceil = Math.ceil(3.1);
System.out.println(ceil);//4.0
//4.floor 向下取整数,返回<=改参数的最大整数
double floor = Math.floor(2.9);
System.out.println(floor);//2.0
//5.round 四舍五入 Math.floor(该参数+0.5);
long round = Math.round(3.6);
System.out.println(round);//4
//6.sqrt 求开发
double sqrt = Math.sqrt(9.0);
System.out.println(sqrt);//3.0
//7.random 求随机数
/* random 返回的是0<=X<1 之间的一个随机小数 a=2,b=7
写出获取a-b之间的一个随机整数,a,b均为整数?
1.(int)(a) <= x < (int)(a+Math.random() *(b-a+1)
2.(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*/
int a=2;
int b=7;
for (int i = 0; i < 100; i++) {
int c = (int)(a+Math.random()*(b-a+1));
System.out.print(c+" ");
}
System.out.println();
//8.max,min返回最大值和最小值
int min = Math.min(1,6);
int max = Math.max(2,7);
System.out.println("min="+min);
System.out.println("max="+max);
Arrays类
Arrays里面包含了一系列静态方法,用于管理或操作的数组(比如排序和搜索)。
1.toString 返回数组的字符串形式(Arrays.toString(arr))
2.sort 排序 (自然排序和定制排序) Integer arr[] = {1,-1,8,0};
3.binarySearch 通过二分搜索法进行查找,要求必须排好序
int index = Arrays.binarySearch(arr,3);
4.copyOf 数组元素的复制
5.fill 数组元素的填充
6.equals 比较两个数组元素内容时否完全一致
7.asList 将一组值,转换成list
点击查看代码
Integer[] integers = {1,3,8,2,7,4};
// 1.toString 返回数组的字符串形式(Arrays.toString(arr)
System.out.println(Arrays.toString(integers));
// 2.sort 排序 (自然排序和定制排序) Integer arr[] = {1,-1,8,0};
/*
1.可以直接使用冒泡排序,也可以直接使用Arrays提供的sort方法排序
2.因为数组是引用类型,所以通过sort排序后,会直接影响到 实参integers
3.sort重载的,也可以通过传入英特接口 Comparator 实现定制排序
4.调用 定制排序 时,传入两个参数(1) 排序的数组 integers
(2) 实现了comparator 接口的匿名内部类,要求实现 compare方法
5.源码分析
1 Arrays.sort(integers, 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) 01;
Integer i2 = (Integer) 02;
return i2-i1;
}
});
5 public int compare(Object o1, Object o2) 返回的值>0 或 <0
会影响整个排序的结果,这就充分体现了 接口编程+动态绑定+匿名内部类的综合使用
*/
//Arrays.sort(integers);//默认排序方法
//定制排序
Arrays.sort(integers, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Integer i1 = (Integer) 01;
Integer i2 = (Integer) 02;
return i2-i1;
}
});
System.out.println(Arrays.toString(integers));
点击查看代码
Integer[] arr = {10,3,2,8,60,7};
//3.binarySearch 通过二分搜索法进行查找,要求必须排序
/*
1.使用 binarySearch 二分查找
2.要求该数组是有序的,如果该数组是无序的,不能使用binarySearch
3.如果不存在该元素,返回 return -(low+1); //key not found
*/
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
int index = Arrays.binarySearch(arr,10);
System.out.println("index = "+index);
//4.copyOf 数组元素的复制
// 1.从arr 数组中,拷贝 arr.length个元素到 newArr数组中
// 2.如果拷贝的长度>arr.length就在新数组的后面增加 null
// 3.如果拷贝长度<0 就跑出异常 NegativeArraySizeException
// 4. 该方法的底层使用的是 System.arraycopy()
Integer[] newArr = Arrays.copyOf(arr,arr.length);
System.out.println(Arrays.toString(newArr));
//5.fill 数组元素的填充
// 使用99去填充num数组,可以理解成事替换原来的元素
Integer[] num = new Integer[]{2,1,7};
Arrays.fill(num,20);
System.out.println(Arrays.toString(num));
//6.equals 比较两个数组元素内容时否完全一致
// 1.如果 arr 和 arr2 数组的元素一样,则方法true
// 2.如果不一样返回false
Integer[] arr2 = {10,3,2,8,60,7};
boolean equals = Arrays.equals(arr,arr2);
System.out.println("equals =" +equals);
//7.asList 将一组值,转换成list
// 1.asList方法,会将(1,3,6,2,4)数据转成一个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<Integer> asList = Arrays.asList(1,3,6,2,4);
System.out.println("asList = " + asList);
System.out.println("asList运行类型"+asList.getClass());
练习
自定义Book类,里面包含了name和Price,按price排序(从大到小)。要求使用两种方式排序,有一个Book[] books = 4本书对象
使用前面学习过的传递 实现Comparator接口匿名内部类,也成为了定制排序。
可以按照price(1)从大到小(2)从小到大(3)按照书名长度
点击查看代码
public static void main(String[] args) {
Book[] book = new Book[4];
book[0] = new Book("红楼梦",100);
book[1] = new Book("水浒",120);
book[2] = new Book("青年文摘",130);
book[3] = new Book("java初级",90);
//从小到大
Arrays.sort(book, new Comparator() {
//这里是对BOOK数组排序,因此o1和o2就是book对象
@Override
public int compare(Object o1, Object o2) {
Book b1 = (Book)o1;
Book b2 = (Book)o2;
double val = b1.getPrice()- b2.getPrice();
if (val>0){
return 1;
}else if(val<0){
return -1;
}else {
return 0;
}
}
});
System.out.println(Arrays.toString(book));
//价格从大到小
Arrays.sort(book, new Comparator() {
//这里是对BOOK数组排序,因此o1和o2就是book对象
@Override
public int compare(Object o1, Object o2) {
Book b1 = (Book)o1;
Book b2 = (Book)o2;
double val = b1.getPrice()- b2.getPrice();
if (val>0){
return -1;
}else if(val<0){
return 1;
}else {
return 0;
}
}
});
System.out.println(Arrays.toString(book));
//按照书名的长度
Arrays.sort(book, new Comparator() {
//这里是对BOOK数组排序,因此o1和o2就是book对象
@Override
public int compare(Object o1, Object o2) {
Book b1 = (Book)o1;
Book b2 = (Book)o2;
double val = b1.getName().length()-b2.getName().length();
if (val>0){
return -1;
}else if(val<0){
return 1;
}else {
return 0;
}
}
});
System.out.println(Arrays.toString(book));
}
class Book{
private String name;
private int price;//价格
public Book(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", price=" + price +
'}'+"\n";
}
}
System类
1.exit退出当前程序
2.arraycopy:复制数组元素,比较适合底层调用,一般使用 Arrays.copyOf 完成复制数组。
3.currentTimeMillis:返回当前时间距离1970-1-1的毫秒数
4.gc:运行垃圾回收机制System.gc();
点击查看代码
//1.exit退出当前程序
System.out.println("ok");
//exit(0)表示程序退出 0表示一个状态,正常的状态
//System.exit(0);
System.out.println("ok2");
//2.arraycopy:复制数组元素,比较适合底层调用一般使用 Arrays.copyOf 完成复制数组。
/*
源数组
//src:代表源数组
src – the source array.
//srcPos:从源数组的哪个索引开始拷贝
srcPos – starting position in the source array.
//dest:目标数组,即把源数组的数据拷贝到哪个数组
dest – the destination array.
//destPos:把源数组的数据拷贝到 目标数组的哪个索引
destPos – starting position in the destination data.
//length:从源数组拷贝多少个
length – the number of array elements to be copied.
*/
int[] src = {1,2,3};
int[] dest = new int[3];//dest 当前是 0 0 0
System.arraycopy(src,0,dest,1,2);
System.out.println(Arrays.toString(dest));
//3.currentTimeMillis:返回当前时间距离1970-1-1的毫秒数
System.out.println(System.currentTimeMillis());
BigInteger和BigDecimal类
1.add 加
2.subtract减
3.multiply乘
4.divide除
点击查看代码
//当编程中,需要处理很大的整数long不够用时 可以使用 BigInteger 的类来完成
BigInteger bigInteger = new BigInteger("29999999999999999999933");
BigInteger bigInteger2 = new BigInteger("100");
System.out.println(bigInteger);
//1.在对BigInteger进行加减乘除的时候,需要使用对应的方法,不能直接进行+-*/
//2.可以创建一个 要操作的 BigInteger 进行操作
BigInteger add = bigInteger.add(bigInteger2);
System.out.println(add);//加法
BigInteger subtract = bigInteger.subtract(bigInteger2);
System.out.println(subtract);//减
BigInteger multiply = bigInteger.multiply(bigInteger2);
System.out.println(multiply);//乘
BigInteger divide = bigInteger.divide(bigInteger2);
System.out.println(divide);//除
//当编程中,需要处理很大的整数double不够用时 可以使用 BigDecimal 的类来完成
BigDecimal bigDecimal = new BigDecimal("123.9999999999999999999999");
BigDecimal bigDecima2 = new BigDecimal("0.00000000000000000001");
System.out.println(bigDecimal);
System.out.println(bigDecimal.add(bigDecima2));//加
System.out.println(bigDecimal.subtract(bigDecima2));//减
System.out.println(bigDecimal.multiply(bigDecima2));//乘
System.out.println(bigDecimal.divide(bigDecima2));//除,无限循环小数时会抛异常
//在调用 divide 方法时,指定精度即可
System.out.println(bigDecimal.divide(bigDecima2,BigDecimal.ROUND_CEILING));//除,无限循环小数时会抛异常
Date、Calendar、Localdate
Date
Date:精确到毫秒,代表特点的时间
SimpleDateFormat:格式和解析日期的类。SimpleDateFormat格式化和解析日期的具体类。它允许镜像格式化(日期→文本)、(文本→日期)和规范化
点击查看代码
//第一代日期
//1,获取当前系统时间
//2.这里的Date 类 是在 java.util包
//3.默认输出的日期格式时国外的方式,因此我们通常需要对格式进行转换
Date d1 = new Date();//获取当前系统时间
System.out.println("当前日期="+d1);
Date d2 = new Date(3123123);//通过指定毫秒数得到时间
System.out.println(d2.getTime());//获取某个时间对应的毫秒数
//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);
String format02 = sdf.format(parse);
System.out.println(format02);
Calender
第二代日期类
1.第二代日期类,主要就是 Calender 类(日历)
2.Calender类是一个抽象类,它为特定瞬间与一组诸如YEAR,MONTH,DAY_OF_MONTH,HOUR等日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。
点击查看代码
//第二代日期
//1.Calendar是一个抽象类,并且构造器是private
//2.可以通过 getInstance() 来获取实例
//3.提供大量的方法和字段提供给程序员
//4.Calendar没有提供对应的格式化的类,因此需要自己组合来输出(灵活)
//5.如果我们需要按照24小时进制来获取时间,Calendar.HOUR改成Calendar.HOUR_OF_DAY
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.HOUR_OF_DAY));
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.DAY_OF_MONTH)+"日");
LocalDate类
第三代日期类
前面两袋日期类的不足分析:
JDK 1.0中包含了一个java.util.Date类,但是它的大多数方法已经在JDK1.1引入 Calender 类之后被弃用了。二 Calender 也存在问题是:
1.可变性:箱日期和时间这一的类应该是不可变的。
2.偏移性:Date中的年份是从1900开始的,而月份都从0开始
3.格式化:格式化只对Date有用,Calendar则不行。
4.此外,他们也不是线程安全的;不能处理闰秒等(每隔两天,多出一秒)
点击查看代码
//第三代日期
//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:ss ");
String s = dtf.format(ldt);
System.out.println(s);
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);
//提供了 plus 和 minus 方法可以对当前的时间进行加或减
//看看890天后,是什么时候 把 年月日 时分秒拿出来
LocalDateTime localDateTime = ldt.plusDays(890);
System.out.println("890天后:"+dtf.format(localDateTime));
//看看在 3456分钟前是什么时候,把年月日时分秒拿出来
LocalDateTime localDateTime12 = ldt.minusMinutes(3456);
System.out.println("3456分钟前:"+dtf.format(localDateTime12));
//1.通过 静态方法 now() 获取表示当前时间戳的对象
Instant now = Instant.now();
System.out.println(now);
//2.通过 from 可以把 Instant 转成 Date
Date date = Date.from(now);
System.out.println(date);
//3.通过 date.toInstant() 可以把 date 转成 Instant 对象
Instant i = date.toInstant();
System.out.println(i);
作业
1编程题
1.将字符串中指定部分进行反转。比如将"abcdef"反转为"aedcbf"
2.方法public static String reverse(String str,int start, int end)
点击查看代码
public static void main(String[] args) {
String str = "abcdef";
try {
System.out.println(revers(str,1,4));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
// 1.将字符串中指定部分进行反转。比如将"abcdef"反转为"aedcbf"
// 2.方法public static String reverse(String str,int start, int end)
/*
先把方法定义确定
把String转成char[],因为char[]是可以交换的
*/
public static String revers(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();
char temp = ' ';//交换辅助遍历
for (int i =start,j=end;i<j;i++,j--){
temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
//使用chars 重新构建一个String 返回即可
return new String(chars);
}
2编程题
输入用户名、密码、邮箱,如果信息录入正确,则提示注册成功,否则生成异常对象要求:
1.用户名长度为2或3或4
2.密码的长度为6,要求全是数字
3.邮箱中包含@和.并且@在.的前面 isDigital
点击查看代码
public static void main(String[] args) {
String name ="asd";
String pwd ="123456";
String email ="asd@qweqw.qwe";
try {
userRegister(name,pwd,email);
System.out.println("恭喜注册成功");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
/*
输入用户名、密码、邮箱,如果信息录入正确,则提示注册成功,否则生成异常对象要求:
1.用户名长度为2或3或4
2.密码的长度为6,要求全是数字
3.邮箱中包含@和.并且@在.的前面 isDigital
思路分析:
1.编写方法userRegister(String name,String pwd,String email){}
2.针对 输入的内容进行校对,如果发现有问题,就抛出异常,给出提示
*/
public static void userRegister(String name,String pwd,String email){
int userLength = name.length();
if (!(userLength >=2 && userLength<=4)) {//
throw new RuntimeException("用户名长度为2或3或4");
}
if(!(pwd.length()== 6 && isDigital(pwd))){
throw new RuntimeException("密码的长度为6,要求全是数字");
}
int a = email.indexOf('@');
int b = email.indexOf('.');
if(!(a>0 && b>a)){
throw new RuntimeException("邮箱中包含@和.并且@在.的前面");
}
}
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;
}
3编程题
1.编写java程序,输入形式为:Han shun Ping的人名,以Ping,Han.S的形式打印出来。其中.S是中间单词的首字母
2.例如输入"Willian Jefferson Clinton",输入形式为:Clinton,Willian.J
点击查看代码
public static void main(String[] args) {
String name = "Willian Jefferson Clinton";
System.out.println(name);
printName(name);
}
/*
1.编写java程序,输入形式为:Han shun Ping的人名,以Ping,Han.S的形式打印出来。
其中.S是中间单词的首字母
2.例如输入"Willian Jefferson Clinton",输入形式为:Clinton,Willian.J
思路分析
1对输入的字符串进行分割split("")
2对得到的String[] 进行格式化 String.format()
3对输入的字符串进行校验即可
*/
public static void printName(String str){
if(str == null){
System.out.println("str 不能为空");
}
String[] names = str.split(" ");
if(names.length != 3){//判断 数组内容是不是有三个下标
System.out.println("输入的字符串格式不对");
return;
}
String format = String.format("%s,%s.%c",names[2],names[0],names[1].toUpperCase().charAt(0));
System.out.println(format);
}
4编程题
输入字符串,判断里面有多少个大写字母,多少个小写字母,多少个数字
点击查看代码
public static void main(String[] args) {
String str = "asdASD123sadASasdDA12321SDAS";
countStr(str);
}
/*
输入字符串,判断里面有多少个大写字母,多少个小写字母,多少个数字
思路分析
1遍历字符串,如果char 在'0'~'9'就是一个数字
2如果char在'a'~'z'就是一个小写字母
3如果char在'A'~'Z'就是一个大写字母
4使用三个遍历来记录统计的结果
*/
public static void countStr(String str) {
if (str == null) {
System.out.println("输入的字符串不能为空");
return;
}
int numCount = 0;//数字
int lowerCount = 0;//小写字母
int upperCount = 0;//大写字母
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {//char 在'0'~'9'就是一个数字
numCount++;
} else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {//char在'a'~'z'就是一个小写字母
lowerCount++;
} else if (str.charAt(i) > 'A' && str.charAt(i) <= 'z') {//如果char在'A'~'Z'就是一个大写字母
upperCount++;
}
}
System.out.println("数字有="+numCount+" 小写字母有="+lowerCount+" 大写字母有="+upperCount);
}
5试着写出以下运行结果//F,F,T,F,F,T
点击查看代码
class Animal {
String name;
public Animal(String name) {
this.name = name;
}
}
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);
}

浙公网安备 33010602011771号