03.java面向对象-常用类
01. 包装类
1. 包装类的分类 Wrapper
- 针对八种基本数据类型相应的应用类型-包装类
- 有了类的特点,就可以调用类中的方法
| 基本数据类型 | 包装类 |
| ------------ | ----------- |
| boolean | Boolean |
| char | Character |
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
public class WrapperType {
public static void main(String[] args) {
//Boolean
//char -- Character
//byte -- Byte
//short -- Short
//int -- Integer
//long -- Long
//float -- Float
//double -- double
}
}
2. 包装类和基本数据的转换
演示包装类和基本数据的转换
- jdk5 前手动装箱和拆箱的方式,装箱:基本类型-包装类型,反之拆箱
- jdk5 以后的自动装箱和拆箱方式
- 自动装箱底层调用的是valueOf方法,比如Integer.valueOf()
- **备注:**包装类主要用于将基本数据类型转换为对象(装箱)以及将对象转换为基本数据类型(拆箱)。
- 其他包装类的用法类似
public class Integer01 {
public static void main(String[] args) {
//1. jdk前是手动装箱和拆箱
//手动装箱
int n1 = 100;
Integer integer = new Integer(n1);
Integer integer1 = Integer.valueOf(n1);
//手动拆箱
int i = integer.intValue();
//2. jdk5 就可以自动装箱
int n2 = 200;
//自动装箱 int -> Integer
Integer integer2 = n2;//底层使用的是 Integer.valueOf(n2)
//自动拆箱
int n3 = integer2;//底层使用的是 Integer intValue()方法
}
}
3. 包装类型和String类型的相互转换
1. 案例演示 以Integer和String装换为例,其他类似:
public class WrapperVSString {
public static void main(String[] args) {
//1. 包装类(Integer --> String)
Integer i = 100;//自动装箱
//方式1 对于原类型没有影响
String str = i + "";
//方式2 使用toString方法
String str2 = i.toString();
//方式3
String str3 = String.valueOf(i);
//2. String --> 包装类(Integer)
String str4 = "1234";
Integer i2 = Integer.parseInt(str4);//自动装箱
//方式2
Integer i3 = new Integer(str4);
}
}
4. Integer和Character类的常用方法
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'));//转成小写
}
}
02. String类
1. String类的理解和创建对象
- String 对象用于保存字符串,也就是一组字符序列
- 字符串常量对象是用双引号引起的字符序列。例如:“你好”、“1.343”、“boy”等
- 字符串的字符使用Unicode字符编码,一个字符(不区分字母还是汉字)占两个字节
- String类常用构造器:
String s1 = new String();
String s2 = new String(String original);
String s3 = new String (char[] a);
String S4 = new String(char[], int startIndex, int count); - String类实现了Serializable接口,说明String 可以串行化
- String类实现了Comparable接口,说明String类可以进行比较
- String 是final类,不能被其他类继承
- String 有属性 private final char value[]; 用于存放字符串内容
- 重点:value是一个final类型,不可以修改(指的 不是是值不能修改,而是地址不能被修改)
2. 两种创建String对象的区别
方式一:直接赋值String s = “yzj”;
方式二:调用构造器 String s2 = new String(“yzj”);
- 方式一:先从常量池查看是否有“yzj”数据空间,如果有直接指向;如果没有则重新创建,然后指向。s最终指向的是常量池的空间地址
- 方式二:先从对中创建空间,里面维护了value属性,指向常量池的yzj空间。如果常量池中没有“yzj”,重新创建,如果有直接通过value指向。最终指向的是堆中的空间地址。
02. String类的常见方法
1. 说明
String类是保存字符串常量。每次更新都需要开辟空间,效率较低,因此java设计者还提供了StringBuilder 和 StringBuffer 来增强String的功能,并提高效率
2. String类常见方法一览
- equals:区分大小写,判断内容是否相等
- equalsIgnoreCase:忽略大小写判断内容是否相等
- length:获取字符的个数,字符串的长度
- indexOf:获取字符在在字符串中第一次出现的索引,索引从零开始,如果找不到,返回-1
- lastiIndexOf:获取字符在字符串中最后一次的索引,索引从零开始,如果找不到,返回-1
- substring:获取指定范围的字符串
- trim:去掉前后空格
- charAt:获取某处索引外的字符,注意不能使用Str[index] 这种方式
String str = “hello”
str[0] 错误的
str.charAt(0) => h 正确
/**
* String 常用方法
**/
public class StringMethod {
public static void main(String[] args) {
//1. equals 前面已经讲过了. 比较内容是否相同,区分大小写
String str1 = "hello";
String str2 = "Hello";
System.out.println(str1.equals(str2));//
// 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(2,5)表示从索引 0 开始截取,截取到索引 5-1=4 位置
System.out.println(name.substring(2, 5));//llo
}
}
3. String类常见方法一览2
- toUpperCase:转换成大写
- toLowerCase:转换成小写
- concat:拼接字符
- replace:替换字符串中的字符
- split:分割字符串中的字符,对于某些分割字符,我们需要转义比如| \\等
案例:String poem = “锄禾日当午,汗滴禾下土,谁知盘中餐,粒粒皆辛苦”; 和文件路径 - compareTo:比较两个字符串的大小
- toCharArray:转换成字符数组
- format:格式字符串,%s字符串 %c字符 %d 整型 %.2f 浮点型
案例将一个人的信息格式化输出
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 没有任何影响
String s11 = s1.replace("宝玉", "jack");
System.out.println(s1);//宝玉 and 林黛玉 林黛玉 林黛玉
System.out.println(s11);//jack and 林黛玉 林黛玉 林黛玉
// 5.split 分割字符串, 对于某些分割字符,我们需要 转义比如 | \\等
String poem = "锄禾日当午,汗滴禾下土,谁知盘中餐,粒粒皆辛苦";
// 1. 以 , 为标准对 poem 进行分割 , 返回一个数组
// 2. 在对字符串进行分割时,如果有特殊字符,需要加入 转义符 \
String[] split = poem.split(",");
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";
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 + "。希望大家喜欢我!";
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);
}
}
03. StringBuffer类
1. 基本介绍
- java.lang.StringBuffer代表可变字符序列,可以对字符串内容进行增删
- 很多方法与String相同,但StringBuffer是可变长度的。
- StringBuffer是一个容器
- 线程安全:StringBuffer 是线程安全的,这意味着多个线程可以同时操作同一个
public class StringBuffer01 {
public static void main(String[] args) {
//1. StringBuffer 的直接父类 是 AbstractStringBuilder
//2. StringBuffer 实现了Serializable ,即StringBuffer的对象可以串行化
//串行化:可以通过网络传输
//3. 在父类中,AbstractStringBuffer 有属性 char[] value,不是final
// 该value 数组存放 字符串内容引出存放在堆中的
//4. StringBuffer 是一个final类,不能被继承
StringBuffer stringBuffer = new StringBuffer();
}
}
2. String和StringBuffer的区别
- String保存的是字符常量,里面的值不能改,每次String类的更新实际上就是更改地址,效率较低//private final char value[];
- StringBuffer保存的是字符串变量,里面的值可以更改,每次StringBuffer的更新实际上可以更新内容,不用更新地址,效率较高//char[] value; 这个放在堆里
public class StringBuffer01 {
public static void main(String[] args) {
//1. StringBuffer 的直接父类 是 AbstractStringBuilder
//2. StringBuffer 实现了Serializable ,即StringBuffer的对象可以串行化
//串行化:可以通过网络传输
//3. 在父类中,AbstractStringBuffer 有属性 char[] value,不是final
// 该value 数组存放 字符串内容引出存放在堆中的
//4. StringBuffer 是一个final类,不能被继承
//5. 因为StringBuffer字符内容是存在插入[] value, 所有在变化【增加/删除】
//不用每次都更换地址(即不是每次都是创建新的对象),所以他的效率高于String
StringBuffer stringBuffer = new StringBuffer();
}
}
3. StringBuffer的构造器
- StringBuffer():构造一个其中不带字符的字符串缓冲区,器初始容量为16个字符
- StringBuffer(charSequence seq) :public java.lang.StringBuilder(Charquence seq)构造一个字符串缓冲区,它包含指定的CharSequence相同的字符
- StringBuffer(int capacity) :构造一个不带字符,但具有指定初始容量的字符串缓冲区,即对char[] 大小进行指定
- StringBuffer(String str):构造一个字符串缓冲区,并将其内容初始化为指定的字符串内容
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[] 大小就是 hello.length() = 16
StringBuffer hello = new StringBuffer("hello");
}
}
4.String和StringBuffer相互转换
- 开发中经常会将String和StringBuffer进行相互转换
案例:
public class StringAndStringBuffer {
public static void main(String[] args) {
// 1. String -> StringBuffer
String str = "hello";
//方式1 使用构造器
//注意:返回的才是StringBuffer对象, 对str本身没有影响
StringBuffer stringBuffer = new StringBuffer(str);
//方式2 使用append方法
StringBuffer stringBuffer1 = new StringBuffer();
//2. StringBuffer -> String
StringBuffer stringBuffer3 = new StringBuffer("hello");
//方式1 使用StringBuffer提供的toString方法
String s = stringBuffer3.toString();
//方式 使用构造器
String s1 = new String(stringBuffer3);
}
}
4. StringBuffer类常见方法
- append:增
- delete(start,end):删
- replace(start, end, string):改 //将start----end 之间的内容替换掉,不含end
- indexOf //查找子串在字符串第一次出现的索引,如果找不到返回-1
- insert:插 insert
- length:获取长度
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);
}
}
04. StringBuilder类
1. 基本介绍
- 一个可变的字符序列。此类提供一个能与StringBuffer兼容的API,但不保证同步(StringBuilder 不是线程安全)。该类被设计用作StringBuffer的一个建议替换,用在字符串缓冲区被单个线程使用的时候。如果可能,建议优先采用该类,因为在大多数实现中,它比StringBuffer要快。
- 在StringBuilder上的主要操作是append和insert方法,可重载这些方法,以接收任意类型的数据。
public class StringBuilder01 {
public static void main(String[] args) {
//1. StringBuilder 继承 AbstractStringBuilder类
//2. 实现了Serializable,说明StringBuilder对象是可以串行化的(对象可以进行网络传输)
//3. StringBuilder 是final类,不可以被继承
//4. StringBuilder 对象字符序列任然是存放在其父类 AbstractStringBuilder的 char[] value
//5. StringBuilder 的方法,没有做互斥的处理,即没有synchronized关键字,因此在单线程的情况下使用
StringBuilder stringBuilder = new StringBuilder();
}
}
2. StringBuilder和StringBuffer的比较
- StringBuilder和StringBuffer非常类似,均可以代表可变的字符序列,而且方法也一样
- String:不可变字符序列效率低,但是复用率高
- StringBuffer:可变字符序列、效率较高(增删)、线程安全
- StringBuilder:可变字符序列,效率最高、线程不安全
3. String使用注意事项
String s = “a”; //创建了一个字符串
s += “b”; //实际上原来的"a"字符串对象已经丢弃了,现在又产生一个字符串 s +“b”(也就是ab)。如果多次知悉丁这些改变串内容的操作,就会导致大量副本字符串对象存留在内存中,降低效率。如果这样的操作放到循环中,会极大影响程序性能。 结论:如果我们要对String进行大量修改就不要用String
05. Math类
1. 基本介绍
Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数
2. 方法一览(均为静态方法)
abs(double a) | 返回double的绝对值 |
---|---|
abs(float a) | 返回float的绝对值 |
abs(int a) | 返回int的绝对值 |
abs(long a) | 返回long的绝对值 |
acos(double a) | 返回一个值的反余弦,返回的角度在0.0 到 pi之间 |
asin(double a) | 返回一个值的反正弦,返回的角度范围在-pi/2 到 pi/2之间 |
atan(double a) | 返回一个值的反正切,返回的角度范围在-pi/2 到 pi/2之间 |
atan2(double y, double x) | 将矩形坐标(x, y) 转换成极坐标(r, theta), 返回所得角theta |
cbrt(double a) | 返回double值的立方根 |
3. 举例演示 Math 类常见的方法
- abs 绝对值
- pow 求幂
- ceil 向上取整
- floor 向下取整
- round 四舍五入
- sqrt 求开方
- random 求随机数 //思考:请写出获取 a-b之间的一个随机整数,a,b均为整数
- max 求两个数的最大值
- min 求两个数的最小值
/**
* 讲解常用的Math类
**/
public class Math01 {
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.9);
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);
}
}
06. Arrays类
Arrays里面包含了一系列静态方法,用于管理或操作数组(比如排序和搜索)
- toString 返回数组的字符形式
Arrays.toString(arr) - sort 排序(自然排序和定制排序) Integer arr[] = {1, -1, 7, 0, 89};
- binarySearch 通过二分法进行查找,要求必须排好序
int index =Arrays.binarySearch(arr,3); - copyOf 数组元素复制
Integer[] newArr = Arrays.copyOf(arr, arr.length); - fill 数组元素的填充
Integer[] num = new Integer[] {9, 3, 2}; - equals 比较两个数组元素内容是否完全一致
boolean equals = Arrays.equals(arr, arr2); - asList 将一组值,转换成list
List<Integer> asList = Arrays.asLis{2, 3, 4, 5, 1};
public class ArraysMethod01 {
public static void main(String[] args) {
// Integer[] integers = {1, 20, 90};
// //以前我们遍历数组用for循环
// //Arrays类提供了一个toString方法,显示数组
// System.out.println(Arrays.toString(integers));
//演示sort方法的使用
Integer[] arr = {1, -1, 7, 0, 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 i2 - i1;
}
});
}
}
补充:
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 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 - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > 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 - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (c.compare(arr[j], arr[j + 1])> 0) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
import java.util.Arrays;
import java.util.List;
public class ArraysMethod02 {
public static void main(String[] args) {
Integer[] arr = {1, 2, 34, 545, 2344};
//binarySearch 通过二分法进行查找,要求必须排好序
//int index =Arrays.binarySearch(arr,3);
//1. 使用binarySearch 二叉查找
//2. 要求数组是要许的,如果该数组是无序的,不能使用binarySearch
//3. 查找数组中的数字,返回下标索引
//4. 如果数组中不存在这个元素,就返回-(low + 1) low是基于你这个数字大小原本它该在的索引位置,例如35 它在数组中不存在在的话应该在第4位
int index = Arrays.binarySearch(arr, 5641);
System.out.println("index = " + index);
//copyOf 数组元素的复制
//1. 从arr数组中,拷贝arr.length个元素到 newArr数组中
//2. 如果拷贝长度 > arr.length 就在新数组后面增加 null
//3. 如果拷贝长度 < 0 就抛出异常
//4. 该方法底层使用的 System.arraycopy()
Integer[] newArr = Arrays.copyOf(arr, arr.length);
System.out.println("拷贝完成后");
System.out.println(Arrays.toString(newArr));
//fill 数组填充
Integer[] num = {1, 2, 3};
System.out.println(Arrays.toString(num));
Arrays.fill(num, 34);
//1. 使用34 替换所有的元素
System.out.println(Arrays.toString(num));
//equals 比较两个数组元素内容是否完全一致
Integer[] arr2 = {1, 2, 34, 456};
boolean equals = Arrays.equals(arr, arr2);
System.out.println(equals);//false
//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<Integer> asList = Arrays.asList(2, 3, 4, 5, 6, 1);
System.out.println(asList);
}
}
07. System类
1. System类常见方法和案例
- exit退出当前程序
- arraycopy:复制数组元素,比较适合底层调用,一般使用Arrays.copyOf完成数组复制
int[] src = {1, 2, 3};
int[] dest = new int[3];
System.arraycopy(src, 0, dest, 0, 3); - currentTimeMillens: 返回当前时间距离 1970-1-1的毫秒数
- gc:运行垃圾回收机制
import java.util.Arrays;
public class System_ {
public static void main(String[] args) {
// //1. exit结束程序
// System.out.println("ok1");
// //2. 0 表示一个状态,正常的状态
// System.exit(0);
// System.out.println("ok2");
//1.arraycopy:复制数组元素,比较适合底层调用,一般使用Arrays.copyOf完成数组复制
int[] src = {1, 2, 3};
int[] dest = new int[3];//dest:当前是0, 0, 0
//2. 搞清这五个参数
// * @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, 3);
System.out.println("dest = " + Arrays.toString(dest));
//currentTimeMillens: 返回当前时间距离 1970-1-1的毫秒数
System.out.println(System.currentTimeMillis());
}
}
08. BigInteger和BigDecimal类
1. BigInteger和BigDecimal介绍
- BigInterger适合保存较大的整型
- BigDecimal适合保存精度更高的浮点型(小数)
2. BigInteger和BigDecimal常见方法
- add 加
- subtract 减
- multiply 乘
- divide 除
1. BigInteger
import java.math.BigInteger;
/**
* BigInteger类
**/
public class BigInteger_ {
public static void main(String[] args) {
//当我们在编程中,需要处理很大的整数,long不够用
// long l = 654564564546546; //整数过大
BigInteger bigInteger = new BigInteger("9999999999999999999999");
BigInteger bigInteger1 = new BigInteger("111");
System.out.println(bigInteger);
//1. 在对 BigInteger进行加减乘除的时候,需使用对应的方法,不能直接+ - * /
//2. 在进行运算的时候需要一个BigInteger变量
BigInteger add = bigInteger.add(bigInteger1);
System.out.println(add);
BigInteger subtract = bigInteger.subtract(bigInteger1);
System.out.println(subtract);
BigInteger multiply = bigInteger.multiply(bigInteger1);
System.out.println(multiply);
BigInteger divide = bigInteger.divide(bigInteger1);
System.out.println(divide);
}
}
2.BigDecimal
import java.math.BigDecimal;
/**
* BigDecimal类
**/
public class BigDecimal_ {
public static void main(String[] args) {
//使用一个精度很高的数时,double就会进行缩减,不够用
//可以使用Decimal
// double d1 = 1999.111111111111111111111111111112222;
// System.out.println(d1);
BigDecimal bigDecimal = new BigDecimal("1999.1111111111111111113246333");
BigDecimal decimal = new BigDecimal("1.22");
System.out.println(bigDecimal);
//1. 如果对 BigDecimal进行运算,需要使用对应的方法
//加减时必须要创建一个需要操作的BigDecimal
BigDecimal add = bigDecimal.add(decimal);
BigDecimal subtract = bigDecimal.subtract(decimal);
BigDecimal multiply = bigDecimal.multiply(decimal);
// BigDecimal divide = bigDecimal.divide(decimal);//注意有时候会除不净,抛出异常
System.out.println(add + " " + subtract + " " + multiply + " ");
//在调用divide方法时,指定精度即可
//如果有无限循环小数,就会保留分子精度
System.out.println(bigDecimal.divide(decimal, BigDecimal.ROUND_CEILING));
}
}
09.日期类[知道怎么查,会用即可,不用每个方法都背]
1. 第一代日期类
- Date:精确到毫秒,代表特定的瞬间
- SimpleDateFormat:格式化和解析日期的具体类。它允许进行格式化(日期 - 文本)、解析(文本 - 日期)和规范化。
字母 | 日期或时间元素 | 表示 | 示例 |
---|---|---|---|
G | Era标识符 | Text | AD |
y | 年 | Year | 1994: 96 |
M | 年中的月份 | Month | July; Jul; 07 |
w | 年中的周数 | Number | 27 |
W | 月份中的周数 | Number | 2 |
D | 年中的天数 | Number | 189 |
d | 月份中的天数 | Number | 10 |
F | 月份中的星期 | Number | 2 |
E | 星期中的天数 | Text | Tuesday; Tus |
a | Am/pm标记 | Text | PM |
H | 一天中的小时数(0-23) | Number | 0 |
k | 一天中的小时数(1-24) | Number | 24 |
K | am/pm中的小时数(0-11) | Number | 0 |
h | am/pm中的小时数(1-12) | Number | 12 |
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));
}
}
2. 第二代时期类
- 第二代日期类,主要就是Calendar类(日历)
public abstract class Calender extends Object implements Serializable,Cloneable,Comparable<Calendar> - Calendar类是一个抽象类,它为特定瞬间与一组诸如 YEAR, MONTH, DAT_OF_MONTH, HOUR等日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下日期的日期)提供一些方法
import java.util.Calendar;
/**
* 第二代日期类
**/
public class Calendar_ {
public static void main(String[] args) {
//Calendar
//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.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) );
}
}
3. 第三代日期类
1. 前面两代日期类的不足分析
JDK1.0中包含了一个java.util.Date类, 但是它的大多数方法已经在JDK1.1 中引入Calendar类之后被弃用了.而Calendar也存在问题是:
- 可变性: 像日期和时间这样的类应该是不可变的
- 偏移性: Date中的年份是从1900开始的,而月份是从0开始的
- 格式化: 格式化只对Date有用,Calendar则不行
- 此外,他还不是线程安全的;不能处理闰秒等(每隔2天,多出1s)
2. 第三代日期类常见方法
- LocalDate(日期/年月日)、LocalTime(时间/时分秒)、LocalDateTime(日期时间/年月日时分秒) JDK8加入
- LocalDate只包含时间,可以获取时间字段
- LocalDateTimes包含日期+时间,可以获取日期和时间字段
3. DateTimeFormatter格式日期类
类似于SimpleDateFormatter
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(格式);
String str = dtf.format(日期对象);
综合案例:
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();
System.out.println(ldt);
//2. 使用DateTimeFormatter对象来进行格式化
//3. 创建DateTimeFormatter对象
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年 MM月dd日 HH小时mm分钟ss秒");
String format = dtf.format(ldt);
System.out.println(format);
System.out.println("年" + ldt.getYear());
System.out.println("月" + ldt.getMonth());
System.out.println("日" + ldt.getDayOfMonth());
System.out.println("时" + ldt.getHour());
System.out.println("分" + ldt.getMinute());
System.out.println("秒" + ldt.getSecond());
LocalDate now = LocalDate.now();//可获取年月日
LocalTime now1 = LocalTime.now();//可获取时分秒
}
}
4. Instant时间戳
- 类似于Date
提供一系列和Date类转换方式
Instant -> Date:
Date date = Date.from(instant);
Date -> Instant:
Instant Instant = date.toInstant();
import java.time.Instant;
import java.util.Date;
/**
* Instant时间戳
**/
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();
}
}
5. 第三代日期类更多方法
- LocalDateTime类
- MonthDay类:检查重复事件
- 是否是闰年
- 增加日期的某个部分
- 使用plus方法测试增加时间的某个部分
- 使用minus方法测试查看一年前和一年后的日期
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();
System.out.println(ldt);
//2. 使用DateTimeFormatter对象来进行格式化
//3. 创建DateTimeFormatter对象
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年 MM月dd日 HH小时mm分钟ss秒");
String format = dtf.format(ldt);
System.out.println(format);
System.out.println("年" + ldt.getYear());
System.out.println("月" + ldt.getMonth());
System.out.println("日" + ldt.getDayOfMonth());
System.out.println("时" + ldt.getHour());
System.out.println("分" + ldt.getMinute());
System.out.println("秒" + ldt.getSecond());
LocalDate now = LocalDate.now();//可获取年月日
LocalTime now1 = LocalTime.now();//可获取时分秒
//提供 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));
}
}