文章目录
1、Arrays 类
1.1、Arrays 类常见方法
package 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);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "\t");
}
// 结合冒泡 + 定制
bubble02(arr, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Integer i1 = (Integer) o1;
Integer i2 = (Integer) o2;
return i2 - i1;
}
});
System.out.println("\n==定制排序后的情况==");
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 - 1 - i; 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 - 1 - i; j++) {
if (c.compare(arr[j], arr[j + 1]) > 0) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
package 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
int index = Arrays.binarySearch(arr, 90);
System.out.println("90的下标=" + index); // 90的下标=2
int index1 = Arrays.binarySearch(arr, 30); // 将30放在数组中, 如果存在直接返回下标,
// 如果不存在, 将该数放在数组的合适位置,
// 然后返回 -(该数组的下标位置 + 1) 对应的值
System.out.println("30的下标=" + index1); // 30的下标=-3 - (2 + 1) => -3
// 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("==拷贝执行完毕后==");
System.out.println(Arrays.toString(newArr)); // [1, 2, 90, 123, 567]
// ill 数组元素的填充
Integer[] num = new Integer[]{9,3,2};
// 1.使用 99 去填充 num 数组, 可以理解成是替换原理的元素
Arrays.fill(num, 99);
System.out.println("==num 数组填充后==");
System.out.println(Arrays.toString(num)); // [99, 99, 99]
// equals 比较两个数组元素内容是否完全一致
Integer[] arr2 = {1, 2, 90, 123};
// 1. 如果 arr 和 arr2 数组的元素一样, 则方法 true
// 2. 如果不是完全一样, 就返回 false
boolean equals = Arrays.equals(arr, arr2);
System.out.println("equals=" + equals); // 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=" + asList); // asList=[2, 3, 4, 5, 6, 1]
System.out.println("asList的运行类型是" + asList.getClass()); // asList的运行类型是class java.util.Arrays$ArrayList
}
}
1.2、Arrays 类小练习
package arrays_;
import java.util.Arrays;
import java.util.Comparator;
public class ArrayExercise {
public static void main(String[] args) {
/*
案例: 自定义 Book 类, 里面包含 name 和 price, 按 price 排序(从大到小)
要求使用两种方式排序, 有一个 Book[] books = 4 本书对象, 使用前面学习过的传递 实现 Comparator 接口匿名内部类, 也称为定制排序
可以按照 price (1)从大到小 (2)从小到大 (3) 按照书名长度从大到小
*/
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);
// (1) price 从大到小
Arrays.sort(books, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Book book1 = (Book) o1;
Book book2 = (Book) o2;
if (book2.getPrice() - book1.getPrice() > 0) {
return 1;
} else if (book2.getPrice() - book1.getPrice() < 0) {
return -1;
} else {
return 0;
}
}
});
System.out.println(Arrays.toString(books)); // [Book{name='java 从入门到放弃', price=300.0}, Book{name='红楼梦', price=100.0}, Book{name='金瓶梅新', price=90.0}, Book{name='青年文摘 20 年', price=5.0}]
// (2) price 从小到大
Arrays.sort(books, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Book book1 = (Book) o1;
Book book2 = (Book) o2;
if (book2.getPrice() - book1.getPrice() < 0) {
return 1;
} else if (book2.getPrice() - book1.getPrice() > 0) {
return -1;
} else {
return 0;
}
}
});
System.out.println(Arrays.toString(books)); // [Book{name='青年文摘 20 年', price=5.0}, Book{name='金瓶梅新', price=90.0}, Book{name='红楼梦', price=100.0}, Book{name='java 从入门到放弃', price=300.0}]
// (3) 按照书名长度从大到小
Arrays.sort(books, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Book book1 = (Book) o1;
Book book2 = (Book) o2;
return book2.getName().length() - book1.getName().length();
}
});
System.out.println(Arrays.toString(books)); // [Book{name='java 从入门到放弃', price=300.0}, Book{name='青年文摘 20 年', price=5.0}, Book{name='金瓶梅新', price=90.0}, Book{name='红楼梦', price=100.0}]
}
}
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 void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
2、System 类
2.1、System 类常见方法
package 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"); // 执行完 System.exit(0) 此行不执行了
// arraycopy: 复制数组元素, 比较适合底层调用, 一般使用 Arrays.copyOf 完成复制数组
int[] src = {1, 2, 3};
int[] dest = new int[3]; // dest 当前是 {0,0,0}
// 源数组
// * @param src the source array
// srcPos: 从源数组的哪个索引位置开始拷贝
// * @param srcPos starting position in the source array
// dest: 目标数组, 即把源数组的数据拷贝到哪个数组
// * @param dest the destination array
// destPos: 把源数组的数据拷贝到 目标数组的哪个索引
// * @param destPos starting position in the destination data
// length: 从源数组拷贝多少个数据到目标数组
// * @param length the number of array elements to be copied
System.arraycopy(src, 0, dest, 0, src.length);
System.out.println("dest=" + Arrays.toString(dest)); // dest=[1, 2, 3]
// currentTimeMillens: 返回当前时间距离 1970-1-1的毫秒数
System.out.println(System.currentTimeMillis());
}
}
3、BigInteger 和 BigDecimal 类
3.1、应用场景
3.2、BigInteger 和 BigDecimal 常见方法
3.2.1、BigInteger 代码演示
package BigInteger_;
import java.math.BigInteger;
public class BigInteger_ {
public static void main(String[] args) {
// 当我们编程中, 需要处理很大的整数, long 不够用
// 可以使用 BigInteger 的类
// long l = 23788888899999999999999999999l; // 这个数太大了, 报错
// System.out.println("l=" + l);
BigInteger bigInteger = new BigInteger("23788888899999999999999999999"); // 定义BigInteger的时候不要带long 后面的 l
BigInteger bigInteger2 = new BigInteger("8294897398573984759834759834759843759837859743958738497598437598437543");
System.out.println("bigInteger=" + bigInteger);
// 1. 在对 BigInteger 进行加减乘除的时候, 需要使用对应的方法, 不能直接进行 + - * /
// 2. 可以创建一个 要操作的 BigInteger 然后进行相应操作
BigInteger add = bigInteger.add(bigInteger2); // 通过看源码 add里面带的也必须是 BigInteger的对象
// public BigInteger add(BigInteger val)
System.out.println("add=" + add); // add=8294897398573984759834759834759843759837883532847638497598437598437542
BigInteger subtract = bigInteger.subtract(bigInteger2);
System.out.println("subtract=" + subtract); // 减
BigInteger multiply = bigInteger.multiply(bigInteger2);
System.out.println("multiply=" + multiply); // 乘
BigInteger divide = bigInteger.divide(bigInteger2);
System.out.println("divide=" + divide); // 除
}
}
3.2.2、BigDecimal 代码演示
package BigInteger_;
import java.math.BigDecimal;
public class BigDecimal_ {
public static void main(String[] args) {
// 当我们需要保存一个精度很高的数时, double 不够用
// 可以是 BigDecimal
double d = 1999.111111111119999999935345354353453453459999977788d; // 1999.11111111112 精度不够
System.out.println(d);
BigDecimal bigDecimal = new BigDecimal("1999.11434234234234234234234324234324");
BigDecimal bigDecimal2 = new BigDecimal("3");
System.out.println("bigDecimal=" + bigDecimal); // bigDecimal=1999.11434234234234234234234324234324
// 1. 如果对 BigDecimal 进行运算, 比如加减乘除, 需要使用对应的方法
// 2. 创建一个需要操作的 BigDecimal 然后调用相应的方法即可
System.out.println(bigDecimal.add(bigDecimal2)); // 加
System.out.println(bigDecimal.subtract(bigDecimal2)); // 减
System.out.println(bigDecimal.multiply(bigDecimal2)); // 乘
// System.out.println(bigDecimal.divide(bigDecimal2)); // 除 // 可能抛出异常 ArithmeticException异常
// 在调用 divide 方法时, 指定精度即可, BigDecimal.ROUND_CEILING
// 如果有无限循环小数, 就会保留 分子 的精度
System.out.println(bigDecimal.divide(bigDecimal2, BigDecimal.ROUND_CEILING));
}
}
4、日期类
4.1、第一代日期类
package 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); // 当前日期=Fri Dec 10 21:11:15 CST 2021
Date d2 = new Date(9234567); // 通过指定毫秒数得到时间
System.out.println("d2=" + d2); // d2=Thu Jan 01 10:33:54 CST 1970
// 1. 创建 SimpleDateFormat 对象, 可以指定相应的格式
// 2. 这里的格式使用的字母是规定好, 不能乱写
SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年 MM 月 dd 日 hh:mm:ss E");
String format = sdf.format(d1); // format: 将日期转换成指定格式的字符串
System.out.println("当前日期=" + format); // 当前日期=2021 年 12 月 10 日 09:11:15 星期五
// 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=" + parse); // parse=Mon Jan 01 10:20:30 CST 1996
}
}
4.2、第二代日期类
package date_;
import java.util.Calendar;
public class Calendar_ {
public static void main(String[] args) {
// 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); // c=java.util.GregorianCalendar[time=1639142265970,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2021,MONTH=11,WEEK_OF_YEAR=50,WEEK_OF_MONTH=2,DAY_OF_MONTH=10,DAY_OF_YEAR=344,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=17,SECOND=45,MILLISECOND=970,ZONE_OFFSET=28800000,DST_OFFSET=0]
// 6.获取日历对象的某个日历字段
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)); // 2021-12-10 21:20:14
}
}
4.3、第三代日期类
package 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); // 2021-12-10T21:26:03.594
// 2. 使用 DateTimeFormatter 对象来进行格式化
// 创建 DateTimeFormatter 对象
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format = dateTimeFormatter.format(ldt);
System.out.println("格式化的日期=" + format); // 格式化的日期=2021-12-10 21:26:03
System.out.println("年=" + ldt.getYear()); // 年=2021
System.out.println("月=" + ldt.getMonth()); // 月=DECEMBER
System.out.println("月=" + ldt.getMonthValue()); // 月=12
System.out.println("日=" + ldt.getDayOfMonth()); // 日=10
System.out.println("时=" + ldt.getHour()); // 时=21
System.out.println("分=" + ldt.getMinute()); // 分=26
System.out.println("秒=" + ldt.getSecond()); // 秒=3
LocalDate now = LocalDate.now(); // 可以获取年月日
LocalTime now2 = LocalTime.now(); // 获取到时分秒
// 提供 plus 和 minus 方法可以对当前时间进行加或者减
// 890 天后, 是什么时候 "年月日-时分秒"
LocalDateTime localDateTime = ldt.plusDays(890);
System.out.println("890 天后=" + dateTimeFormatter.format(localDateTime)); // 890 天后=2024-05-18 21:26:03
// 3456 分钟前是什么时候 "年月日-时分秒"
LocalDateTime localDateTime2 = ldt.minusMinutes(3456);
System.out.println("3456 分钟前 日期=" + dateTimeFormatter.format(localDateTime2)); // 3456 分钟前 日期=2021-12-08 11:50:03
}
}
4.4、DateTimeFormatter 格式日期类
4.5、Instant 时间戳
package 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=" + now); // now=2021-12-10T13:30:45.378Z
// 2. 通过 from 可以把 Instant 转成 Date
Date date = Date.from(now);
System.out.println("date=" + date); // date=Fri Dec 10 21:31:29 CST 2021
// 3. 通过 date 的 toInstant() 可以把 date 转成 Instant 对象
Instant instant = date.toInstant();
System.out.println("instant=" + instant); // instant=2021-12-10T13:31:52.319Z
}
}