【Java系列】:常用类(下)

😃7 Math 类

🔘7.1 基本介绍

Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。

🔘7.2 方法一览(均为静态方法)

在这里插入图片描述

🔘7.3 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);
    }
}

😉8 Arrays 类

🔘8.1 Arrays 类常见方法应用案例

Arrays里面包含了一系列静态方法,用于管理或操作数组(比如排序和搜索)

  1. toString返回数组的字符串形式
Arrays.toString(arr)
public class ArraysMethod {
    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. sort 排序(自然排序和定制排序)

① 默认排序方法:

public class ArraysMethod02 {
    public static void main(String[] args) {
        //演示 sort 方法的使用
        Integer arr[] = {1, -1, 7, 0, 89};
        //进行排序
        //解读
        //1. 可以直接使用冒泡排序 , 也可以直接使用 Arrays 提供的 sort 方法排序
        //2. 因为数组是引用类型,所以通过 sort 排序后,会直接影响到 实参 arr
        Arrays.sort(arr);
        System.out.println("===排序后===");
        System.out.println(Arrays.toString(arr));
    }
}

② 定制排序

public class ArraysMethod02 {
    public static void main(String[] args) {
        //演示 sort 方法的使用
        Integer arr[] = {1, -1, 7, 0, 89};
        //进行排序
        //解读
        //1. sort 重载的,也可以通过传入一个接口 Comparator 实现定制排序
        //2. 调用 定制排序 时,传入两个参数
        // (1) 排序的数组 arr
        // (2) 实现了 Comparator 接口的匿名内部类 , 要求实现 compare 方法
        //定制排序

        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));
    }
}

🧐分析:
这里体现了接口编程的方式 , 看看源码,就明白!
(1)首先debug 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)
再往下debug就会回到

new Comparator() {
	@Override
	public int compare(Object o1, Object o2) {
		Integer i1 = (Integer) o1;
		Integer i2 = (Integer) o2;
		return i1 - i2;
	}
}

接着往下又去调用
在这里插入图片描述
直到最后排序完毕。
(5) public int compare(Object o1, Object o2) 返回的值>0 还是 <0会影响整个排序结果, 这就充分体现了 接口编程+动态绑定+匿名内部类的综合使用,将来的底层框架和源码的使用方式,会非常常见
😉补充:
这样也行,同样道理,但是用到了泛型(后面再讲)。

Arrays.sort(arr, new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2-o1;
    }
});
  1. binarySearch通过二分搜索法进行查找,要求必须排好序
Integer[] arr = {1, 2, 90, 123, 567};
// binarySearch 通过二分搜索法进行查找,要求必须排好
// 解读
//1. 使用 binarySearch 二叉查找
//2. 要求该数组是有序的. 如果该数组是无序的,不能使用binarySearch
//3. 如果数组中不存在该元素,就返回 return -(low + 1);  // key not found.
int index = Arrays.binarySearch(arr, 567);
System.out.println("index=" + index);

🧐输出结果:

index=4

如果没有找到,就返回 return -(low + 1);
💻演示:

Integer[] arr = {1, 2, 90, 123, 567};
// binarySearch 通过二分搜索法进行查找,要求必须排好
// 解读
//1. 使用 binarySearch 二叉查找
//2. 要求该数组是有序的. 如果该数组是无序的,不能使用binarySearch
//3. 如果数组中不存在该元素,就返回 return -(low + 1);  // key not found.
int index = Arrays.binarySearch(arr, 568);
System.out.println("index=" + index);

🧐输出结果:

index=-6
  1. copyof 数组元素的复制
Integer[] arr = {1, 2, 90, 123, 567};
//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]
  1. fill数组元素的填充
/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));
  1. equals 比较两个数组元素内容是否完全一致
Integer[] arr = {1, 2, 90, 123, 567};
//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
  1. asList将一组值,转换成list
        //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=" + asList);
        System.out.println("asList的运行类型" + asList.getClass());

🧐输出结果:

asList=[2, 3, 4, 5, 6, 1]
asList的运行类型class java.util.Arrays$ArrayList

🔘8.2 模拟定制排序

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author Baridhu
 */
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;// 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 - 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++) {
                //数组排序由 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;
                }
            }
        }
    }
}

运行结果:

==定制排序后的情况==
[20, 8, 1, 0, -1]

😎9 System 类

🔘9.1 System 类常见方法和案例

  1. exit 退出当前程序
//exit 退出当前程序
System.out.println("ok1");
//解读
//1. exit(0) 表示程序退出
//2. 0 表示一个状态 , 正常的状态
System.exit(0);//
System.out.println("ok2");

运行结果:

  1. arraycopy:复制数组元素,比较适合底层调用,一般使用Arrays.copyOf完成复制数组.
//arraycopy :复制数组元素,比较适合底层调用,
// 一般使用Arrays.copyOf完成复制数组

int[] src={1,2,3};
int[] dest = new int[3];// dest 当前是 {0,0,0}

//解读
//1. 主要是搞清楚这五个参数的含义
//2.
//     源数组
//     * @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);
// int[] src={1,2,3};
System.out.println("dest=" + Arrays.toString(dest));//[1, 2, 3]

运行结果:

dest=[1, 2, 3]

代码二:

System.arraycopy(src, 0, dest, 1, 2);
System.out.println("dest=" + Arrays.toString(dest));//[1, 2, 3]

运行结果:

dest=[0, 1, 2]
  1. currentTimeMillens:返回当前时间距离1970-1-1的毫秒数
//currentTimeMillens:返回当前时间距离1970-1-1 的毫秒数
// 解读:
System.out.println(System.currentTimeMillis());

运行结果:

1647249983437
  1. gc:运行垃圾回收机制System.gc();

😁10. BigInteger 和 BigDecimal 类

🔘10.1 背景

Java中的基础数据类型能存储的最大的二进制数是 2 ^ 63 - 1,只要运算过程中会超过这个数,就会造成数据溢出,就会造成错误。但在Java中有两个类BigInteger和BigDecimal分别表示大整数类和大浮点数类,至于两个类的对象能表示最大范围不清楚,理论上能够表示无线大的数,只要计算机内存足够大。

🔘10.2 介绍

📒这两个类都在java.math.*包中,因此每次必须在开头处引用该包;
📒BigInteger实现了任意精度的整数运算;
📒BigDecimal实现了任意精度的浮点数运算。

🔘10.3 方法

** 📚普通的数值转换成大数值**
分别调用BigInteger.valueOf("普通数值"),BigDecimal.valueOf("普通数值")即可。

int a=10;
BigInteger.valueOf(a2);
double a=1.123456;
BigDecimal.valueOf(a);

📚创建

import java.math.BigDecimal;
import java.math.BigInteger;

public class 创建 {
    public static void main(String[] args) {
        //1.直接声明
        BigInteger a;
        BigDecimal b;
        //2.使用构造函数初始化
        BigInteger a1 = new BigInteger("1234567891021212155646");
        BigDecimal b1 = new BigDecimal("123456.756231");

    }
}

📚赋值
使用

BigInteger.valueOf(long val);
BigDecimal.valueOf(double val);

注意:

val 不能超过 long 类型的最大取值9223372036854775807, 超过int时要在数后面加L(int的取值范围为: -231——231-1,即-2147483648——2147483647 )。

import java.math.BigDecimal;
import java.math.BigInteger;

public class 赋值 {
    public static void main(String[] args) {
        //BigInteger.valueOf(long val);
        //BigDecimal.valueOf(double val);
        BigInteger a;
        BigDecimal b;
        //注意 val 不能超过 long 类型的最大取值9223372036854775807, 超过int时要在数后面加L如:
        a = BigInteger.valueOf(123456789101112L); //大于int范围的要加L
        b = BigDecimal.valueOf(123456.12341235); // 超出的小数位数会自动舍弃

    }
}

或者使用

BigInteger a;
BigInteger b = new BigInteger("123456");
a = b;
import java.math.BigInteger;

public class 赋值二 {
    public static void main(String[] args) {
        BigInteger a;
        BigInteger b = new BigInteger("123456");
        a = b;
        System.out.print(a);//123456
    }
}

📚加法
方法add();

import java.math.BigInteger;

public class 加法 {
    public static void main(String[] args) {
        BigInteger a, b, c;
        a = BigInteger.valueOf(123456789); // 赋值为 123456789
        b = BigInteger.valueOf(987654321); // 赋值为 987654321
        c = a.add(b);
        System.out.print(c);
    }
}

📚减法
方法subtract();

import java.math.BigInteger;

public class 减法 {
    public static void main(String[] args) {
        BigInteger a, b, c;
        a = BigInteger.valueOf(123456789); // 赋值为 123456789
        b = BigInteger.valueOf(987654321); // 赋值为 987654321
        c = a.subtract(b);
        System.out.print(c);

    }
}

📚乘法
方法multiply();

import java.math.BigInteger;

public class 乘法 {
    public static void main(String[] args) {
        BigInteger a, b, c;
        a = BigInteger.valueOf(123456789); // 赋值为 123456789
        b = BigInteger.valueOf(987654321); // 赋值为 987654321
        c = a.multiply(b);
        System.out.print(c);

    }
}

📚除法
方法divide();

import java.math.BigInteger;

public class 除法 {
    public static void main(String[] args) {
        BigInteger a, b, c;
        a = BigInteger.valueOf(987654321); // 赋值为 987654321
        b = BigInteger.valueOf(123456789); // 赋值为 123456789
        c = a.divide(b); // 整数相除仍为整数
        System.out.print(c);

    }
}

📚进制转化
使用构造函数BigInteger(String, int index),可以把一个index进制的字符串,转化为10进制的BigInteger。

BigInteger a = new BigInteger("111110", 2);111110从二进制变为10进制赋值给a

a.toString(radix);//把十进制数a转变为radix数进制。

System.out.println(a.toString(16));把a转化为16进制的字符串输出

综合案例:
给定n个十六进制正整数,输出它们对应的八进制数。
答案:

import java.math.BigInteger;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        for(int i=1;i<=n;i++){
            String s = sc.next();
            String s1 = new BigInteger(s,16).toString(8);
            System.out.println(s1);
        }
    }
}

📚求最值

最大值:max();
最小值:min();
BigInteger a, b, c, d;
a = BigInteger.valueOf(987654321);
b = BigInteger.valueOf(12345678); 
c = a.max(b); //a,b中的最大值
d = a.min(b); //a,b中的最小值
System.out.println(c);
System.out.println(d);

输出:

987654321
12345678

📚取余
方法mod();

BigInteger a, b, c;
a = BigInteger.valueOf(987654321); // 赋值为 987654321
b = BigInteger.valueOf(123456789); // 赋值为 123456789
c = a.mod(b);
System.out.print(c);

输出:

9
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值