0%

常用类-2

常用类

Math方法

  • Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。
  1. Math.abs():求绝对值

  2. Math.pow():求幂

  3. Math.ceil():向上取整,返回 >= 该参数的最小整数

  4. Math.floor():向下取整,返回 <= 该参数的最大整数

  5. Math.round():四舍五入 -> Math.floor(参数+0.5)

    即,先将参数 + 0.5,然后将得到的值向下取整

  6. Math.sqrt():求开方

  7. Math.random():求随机数,返回的是 [0,1) 之间的一个随机小数

    [a, b]:(int)(Math.random() * (b-a+1) + a)

  8. Math.max():求最大值

  9. Math.min():求最小值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.f.chapter13;

/**
* @author fzy
* @date 2023/4/26 14:18
*/
public class MathMethod {
public static void main(String[] args) {
//1. abs 求绝对值
double abs = Math.abs(-5.1);
System.out.println(abs); //5.1
//2. pow 求幂
double pow = Math.pow(1.1, 3);
System.out.println(pow); //1.1^3
//3. ceil 向上取整,返回 >= 该参数的最小整数
double ceil = Math.ceil(-5.001);
System.out.println(ceil); //-5.0
//4. floor 向下取整,返回 <= 该参数的最大整数
double floor = Math.floor(-5.001);
System.out.println(floor); //-6.0
//5. round 四舍五入 -> Math.floor(参数+0.5)
long round = Math.round(-5.4);
System.out.println(round); //-5
//6. sqrt 开方
double sqrt = Math.sqrt(10);
System.out.println(sqrt); //根号10
//7. random 求随机数,返回的是 [0,1) 之间的一个随机小数
double random = Math.random();
System.out.println(random);
//8. max 求最大值
double max = Math.max(-1.1, -2.3);
System.out.println(max); //-1.1
//9. min 求最小值
double min = Math.min(-1.1, -2.3);
System.out.println(min); //-2.3
}
}

★Arrays类方法

  • Arrays 里面包含了一系列静态方法,用于管理或操作数组 (比如排序和搜索)。
  1. Arrays.toString(arr):返回数组的字符串形式。

  2. ★**Arrays.sort(arr):排序,默认升序排序。**

    sort 是重载的,可以通过传入一个接口 Comparator 实现定制排序。

    • Arrays.sort(T[] a, Comparator<? super T> c)

      使用定制排序时,需要传入两个参数:(1) 要排序的数组 a;(2) 实现了 Comparator 接口的匿名内部类,要求实现 compare 方法。

  3. Arrays.binarySearch(arr, key):二分查找,要求 arr 必须排好序。

  4. Arrays.copyOf(arr, length):从 arr 数组中,拷贝指定个数个元素。

    如果拷贝的长度大于 arr.length,就在新数组的后面增加0(对于int数组来说), null(对于对象数组来说), false(对于boolean数组来说);

    如果拷贝的长度小于 0,就抛出 NegativeArraySizeException 异常。

  5. Arrays.fill(arr, val):数组元素填充,可以理解为用 val 替换所有原来的元素。

  6. Arrays.equals(arr1, arr2):比较两个数组元素内容是否完全一致,如果一样,则返回true,否则返回false。

  7. Arrays.asList():将一组值转换为 List 集合。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.f.chapter13;

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

/**
* @author fzy
* @date 2023/4/26 14:54
*/
public class ArraysMethod {
public static void main(String[] args) {
//1. toString 返回数组的字符串形式
int[] arr = {1, 2, 3, 5, 8};
System.out.println(Arrays.toString(arr)); //[1, 2, 3, 5, 8]

//2. sort 排序(默认排序和定制排序)
Integer[] integers1 = {-1, 30, 2, 59, -10};
Integer[] integers2 = {-1, 30, 2, 59, -10};
//默认排序
Arrays.sort(integers1);
System.out.println(Arrays.toString(integers1)); //[-10, -1, 2, 30, 59]
//定制排序
/*
* 这里体现了接口编程的方式,看源码可以发现:
* Arrays.sort(T[] a, Comparator<? super T> c) 会调用
* TimSort.sort(a, 0, a.length, c, null, 0, 0); 然后进一步调用
* binarySort(a, lo, hi, lo + initRunLen, c); 二叉树排序,该方法会使用到我们重写的 compare 方法
* if (c.compare(pivot, a[mid]) < 0) 由此来实现定制排序
* */
Arrays.sort(integers2, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
System.out.println(Arrays.toString(integers2)); //[59, 30, 2, -1, -10]

//3. binarySearch 二分查找,要求必须排好序
// 如果没找到,返回的是 return -(low + 1); // key not found.
int index = Arrays.binarySearch(arr, 5);
System.out.println(index); //3

//4. copyOf 数组元素的复制
/*
* 1. 从 arr 数组中,拷贝指定个数个元素到 newArr 数组中
* 2. 如果拷贝的长度大于 arr.length,就在新数组的后面增加0(对于int数组来说),null(对于对象数组来说),false(对于boolean数组来说)
* 3. 如果拷贝的长度小于 0,就抛出 NegativeArraySizeException 异常
* */
int[] newArr = Arrays.copyOf(arr, arr.length + 1);
System.out.println(Arrays.toString(newArr)); //[1, 2, 3, 5, 8, 0]
Integer[] newIntegers = Arrays.copyOf(integers1, integers1.length + 1);
System.out.println(Arrays.toString(newIntegers)); //[-10, -1, 2, 30, 59, null]

//5. fill 数组元素填充
Arrays.fill(arr, 100); //使用 100 去填充 arr 数组,可以理解为替换所有原来的元素
System.out.println(Arrays.toString(arr)); //[100, 100, 100, 100, 100]

//6. equals 比较两个数组元素内容是否完全一致
//如果 integers1 和 integers2 数组的元素一样,则返回true,否则返回false
boolean equals = Arrays.equals(integers1, integers2);
System.out.println(equals); //false

//7. asList 将一组值转换为List集合
List intList = Arrays.asList(1, 2, -3, 7, 8);
System.out.println(intList); //[1, 2, -3, 7, 8]
}
}

★Comparable和Comparator的区别

  • Java语言中,ComparableComparator 都是接口,都可以用来实现集合中元素的比较、排序。

    Comparable 位于包 java.lang 下,而 Comparator 位于包java.util下,**Comparable 接口将比较代码嵌入自身类中,而Comparator既可以嵌入到自身类中,也可以在一个独立的类中实现比较**。

  1. 字面含义不同:Comparable 翻译为中文是“比较”的意思,而 Comparator 是“比较器”的意思。Comparable 是以-able结尾的,表示它自身具备着某种能力,而 Comparator 是以-or结尾,表示自身是比较的参与者,这是从字面含义先来理解二者的不同。

  2. 用法不同:二者都是顶级的接口,但拥有的方法和用法是不同的。

    • Comparable 接口只有一个方法 compareTo,类需要实现 Comparable 接口并重写 compareTo 方法来实现该类的排序Comparable接口支持 Collections.sortArrays.sort 的排序。

      compareTo 方法接收的参数是要进行比较的对象,排序规则是用当前对象和要对比的对象进行比较,然后返回一个int类型的值。

    • ComparatorComparable的排序方法是不同的,类可以不用实现 Comparator 接口,而是在类的外部,不修改原有类的情况下,通过重写 Comparator排序的方法compare 来实现该类的排序。

  3. 使用场景不同:

    • 使用Comparable必须要修改原有的类,也就是你要排序的那个类,要在那个类中实现Comparable接口并重写compareTo方法,所以Comparable更像是“对内”进行排序的接口,可以认为是一个内比较器
    • 使用Comparator无需修改原有类,我们可以通过创建新的自定义比较器Comparator,来实现对原有类的排序功能。也就是说通过Comparator接口可以实现和原有类的解耦,在不修改原有类的情况下实现排序功能,所以Comparator可以看作是“对外”进行排序的接口,可以认为是一个外比较器
  • 看下面关于 ComparableComparator 的例子:

    • 通过实现 Comparable 接口来对类自身的对象进行排序。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      package com.f.chapter13;

      import java.util.ArrayList;
      import java.util.Collections;

      /**
      * @author fzy
      * @date 2023/6/29 18:43
      */
      public class ComparableExercise {
      public static void main(String[] args) {
      ArrayList<Person> people = new ArrayList<>();
      people.add(new Person("tom", 20));
      people.add(new Person("jack", 18));
      people.add(new Person("jerry", 26));
      System.out.println("===排序前===");
      System.out.println(people); //[Person{name='tom', age=20}, Person{name='jack', age=18}, Person{name='jerry', age=26}]
      Collections.sort(people);
      System.out.println("===排序后===");
      System.out.println(people); //[Person{name='jack', age=18}, Person{name='tom', age=20}, Person{name='jerry', age=26}]
      }
      }

      class Person implements Comparable<Person> { //要实现Comparable接口
      private String name;
      private int age;

      public Person(String name, int age) {
      this.name = name;
      this.age = age;
      }

      public String getName() {
      return name;
      }

      public void setName(String name) {
      this.name = name;
      }

      public int getAge() {
      return age;
      }

      public void setAge(int age) {
      this.age = age;
      }

      @Override
      public String toString() {
      return "Person{" +
      "name='" + name + '\'' +
      ", age=" + age +
      '}';
      }

      //要重写compareTo方法
      @Override
      public int compareTo(Person p) {
      return this.age - p.age; //定制的排序方式,这里根据年龄来排序
      //return this.name.compareTo(p.name); //根据名称自然排序
      }
      }
    • 通过 Comparator 接口来对类对象进行排序。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      package com.f.chapter13;

      import java.util.ArrayList;
      import java.util.Collections;
      import java.util.Comparator;

      /**
      * @author fzy
      * @date 2023/6/29 18:51
      */
      public class ComparatorExercise {
      public static void main(String[] args) {
      ArrayList<Person> people = new ArrayList<>();
      people.add(new Person("tom", 20));
      people.add(new Person("jack", 18));
      people.add(new Person("jerry", 26));
      System.out.println("===排序前===");
      System.out.println(people); //[Person{name='tom', age=20}, Person{name='jack', age=18}, Person{name='jerry', age=26}]
      Collections.sort(people, new Comparator<Person>() {
      @Override
      public int compare(Person p1, Person p2) {
      return p1.getAge() - p2.getAge(); ////定制的排序方式,这里根据年龄来排序
      }
      });
      System.out.println("===排序后===");
      System.out.println(people); //[Person{name='jack', age=18}, Person{name='tom', age=20}, Person{name='jerry', age=26}]
      }
      }

      class Person { //不用实现Comparator接口
      private String name;
      private int age;

      public Person(String name, int age) {
      this.name = name;
      this.age = age;
      }

      public String getName() {
      return name;
      }

      public void setName(String name) {
      this.name = name;
      }

      public int getAge() {
      return age;
      }

      public void setAge(int age) {
      this.age = age;
      }

      @Override
      public String toString() {
      return "Person{" +
      "name='" + name + '\'' +
      ", age=" + age +
      '}';
      }
      }

System方法

  1. System.exit():退出当前程序。
  2. System.arraycopy(src, srcPos, dest, destPos, length):复制数组元素,比较适合底层调用,一般我们用Arrays.copyOf完成数组的复制。
  3. System.currentTimeMillis():返回当前时间距离1970-1-1的毫秒数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.f.chapter13;

import java.util.Arrays;

/**
* @author fzy
* @date 2023/4/27 20:44
*/
public class SystemMethod {
public static void main(String[] args) {
//1. exit 退出当前程序
//System.exit(0); //0 表示一个状态,正常的状态

//2. arraycopy 复制数组元素,比较适合底层调用,一般我们用Arrays.copyOf完成数组的复制
/*
* @param src 源数组
* @param srcPos 源数组开始拷贝的位置
* @param dest 目标数组
* @param destPos 目标数组开始粘贴的位置
* @param length 拷贝的元素个数
* */
int[] src = {1, 2, -3, 6, 7};
int[] dest = new int[src.length + 1];
System.arraycopy(src, 0, dest, 0, src.length);
System.out.println(Arrays.toString(dest)); //[1, 2, -3, 6, 7, 0]

//3.currentTimeMillis 返回当前时间距离1970-1-1的毫秒数
System.out.println(System.currentTimeMillis());
}
}

大数处理方案

BigInteger
  • 适合保存比较大的整型。

    在对 BigInteger 进行加减乘除运算的时候,需要使用对应的方法,不能直接进行 + - * /

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    package com.f.chapter13;

    import java.math.BigInteger;

    /**
    * @author fzy
    * @date 2023/4/27 21:03
    */
    public class BigInteger_ {
    public static void main(String[] args) {
    BigInteger bigInteger1 = new BigInteger("12345678987654321");
    BigInteger bigInteger2 = new BigInteger("98765432123456789");
    BigInteger add = bigInteger1.add(bigInteger2); //加
    BigInteger substract = bigInteger1.subtract(bigInteger2); //减
    BigInteger multiply = bigInteger1.multiply(bigInteger2); //乘
    BigInteger divide = bigInteger1.divide(bigInteger2); //除
    System.out.println(add);
    System.out.println(substract);
    System.out.println(multiply);
    System.out.println(divide);
    }
    }
BigDecimal
  • 适合保存精度更高的浮点型。

    运算和 BigInteger 同理,注意 BigDecimal 在做除法时,除不尽的情况要指定保留精度

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    package com.f.chapter13;

    import java.math.BigDecimal;

    /**
    * @author fzy
    * @date 2023/4/27 21:23
    */
    public class BigDecimal_ {
    public static void main(String[] args) {
    BigDecimal bigDecimal1 = new BigDecimal("1.234567890987654321");
    BigDecimal bigDecimal2 = new BigDecimal("0.345678909876543212");
    BigDecimal add = bigDecimal1.add(bigDecimal2); //加
    BigDecimal subtract = bigDecimal1.subtract(bigDecimal2); //减
    BigDecimal multiply = bigDecimal1.multiply(bigDecimal2); //乘
    //BigDecimal divide = bigDecimal1.divide(bigDecimal2); //除,可能抛出异常:Non-terminating decimal expansion; no exact representable decimal result.原因是除不尽
    BigDecimal divide = bigDecimal1.divide(bigDecimal2, BigDecimal.ROUND_CEILING); //在调用divide方法时,指定精度即可
    System.out.println(add);
    System.out.println(subtract);
    System.out.println(multiply);
    System.out.println(divide);
    }
    }
---------------The End---------------