Java基础之:Math & Arrays & System

Java基础之:Math & Arrays & System

Math

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

方法介绍:

  1.abs 绝对值

  2.pow 求幂

  3.ceil 向上取整,返回>=该参数的最小整数;

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

  5.round 四舍五入 Math.floor(该参数+0.5)

  6.sqrt 求开方

  7.random 返回随机数【0——1) ,重点!!

package class_Math;
public class ClassTest01 {
​
    public static void main(String[] args) {
        //1.abs 绝对值
        int abs = Math.abs(9);
        System.out.println(abs);
        //2.pow 求幂
        double pow = Math.pow(-3.5, 4);
        System.out.println(pow);
        //3.ceil 向上取整,返回>=该参数的最小整数;
        double ceil = Math.ceil(-3.0001);
        System.out.println(ceil);
        //4.floor 向下取整,返回<=该参数的最大整数
        double floor = Math.floor(-4.999);
        System.out.println(floor);
        //5.round 四舍五入  Math.floor(该参数+0.5)
        long round = Math.round(-5.001);
        System.out.println(round);
        //6.sqrt 求开方
        double sqrt = Math.sqrt(-9.0);
        System.out.println(sqrt);
        //7.random 返回随机数【0——1)  
        //[a-b]:int num = (int)(Math.random()*(b-a+1)+a)  
        double random = Math.random();
        System.out.println(random);
        
        //小技巧:获取一个 a-b 之间的一个随机整数
        int a = (int)(Math.random()*(15-7+1)+7);
        System.out.println(a);
        /*
         * 理解:
         *  1.Math.random() 是 [0,1)的随机数
         *  2.(Math.random()*(15-7+1) 就是[0,9)
         *  3.Math.random()*(15-7+1)+7 就是[7,16)
         *  4.(int)取整就是 [7,15] ,即[a,b]之间的随机整数
         */
    }
}

 

Arrays

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

Arrays排序sort方法

package class_Arrays;
​
import java.util.Arrays;
import java.util.Comparator;
​
public class ClassTest01 {
    public static void main(String[] args) {
        Integer[] arr = { 25, 35, 11, 32, 98, 22 };
//      Arrays.sort(arr);   //默认小到大排序
        System.out.println(Arrays.toString(arr));
​
        // 使用匿名内部类重写compare方法,实现从大到小排序
        Arrays.sort(arr, new Comparator<Integer>() {
​
            @Override
            public int compare(Integer o1, Integer o2) {
                if (o1 > o2) {
                    return -1;
                } else if (o1 < o2) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        System.out.println(Arrays.toString(arr));
    }
}
​
//自写一个Arrays中的sort方法 体会为什么通过重写之后,匿名内部类动态绑定机制改变了排序方式
class MyArrays {
    @SuppressWarnings("unchecked")
    public static void sort(Integer[] arr,Comparator c) {
        Integer temp = 0;// 自动装箱
        for (int i = 0; i < arr.length; 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;
                }
            }
        }
    }
    
    public static void main(String[] args) {
        Integer[] arr = { 25, 35, 11, 32, 98, 22 };
//      MyArrays.sort(arr);//不添加 Comparator接口对象为参数,就是简单的冒泡排序方法
        
        //添加匿名内部类对象为参数,就可以改变排序方式。用此方法可以很灵活的使用排序。
        MyArrays.sort(arr, new Comparator<Integer>() {
​
            @Override
            public int compare(Integer o1, Integer o2) {
                //通过返回值的正负来控制,升序还是降序 
                //只有当返回值为1时,才会发生交换。例如这里,o1 < o2时返回1 ,进行交换
                //也就是需要前面的数,比后面的数大,即降序
                if (o1 > o2) {  
                    return -1;
                } else if (o1 < o2) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        System.out.println(Arrays.toString(arr));
    }
}

 

Arrays查找binarySearch方法及其他常用方法

package class_Arrays;
​
import java.util.List;
import java.util.Arrays;
​
public class ClassTest02 {
​
    public static void main(String[] args) {
        //随机生成数组,并排序
        Integer[] arr = new Integer[10];
//      for (int i = 0; i < arr.length; i++) {
//          arr[i] = (int)(Math.random()*100) + 1 ;
//      }
//      Arrays.sort(arr);
        arr = new Integer[]{16, 28, 41, 51, 62, 67, 67, 86, 90, 93};
        System.out.println(Arrays.toString(arr));
        
        // binarySearch 通过二分搜索法进行查找,要求必须排好序
        int index = Arrays.binarySearch(arr, 55);   //返回 -5 (55在51和62之间)
        //找到则返回下标,若没有找到则返回-(low + 1)。即此数在数组中应该在的位置的下标 + 1,例:
        //{1,3,5,9,10},此数组中找2,没有找到则返回-2,因为2本来在1和3的中间。下标为1再+1,就是-2
        System.out.println(index);
        
        
        // copyOf 数组元素的复制,参数列表:目标数组,需拷贝元素个数(若超过,使用null填充,若<0,报错)
        Integer[] newArr = Arrays.copyOf(arr, arr.length - 5);
        Integer[] newArr2 = Arrays.copyOf(arr, arr.length + 5);
        System.out.println(Arrays.toString(newArr));
        System.out.println(Arrays.toString(newArr2));
        
        // fill 数组元素的填充,将数组中的所有元素填充为所指定的内容
        Integer[] num = new Integer[] { 9, 3, 2 };
        Arrays.fill(num, 99);
        System.out.println(Arrays.toString(num));
        
        
        //equals 比较两个数组元素内容是否完全一致
        Integer[] array = new Integer[]{1,2,3};
        Integer[] array2 = new Integer[]{1,2,3};
        boolean equals = Arrays.equals(array, array2);
        System.out.println(equals); 
        
        //asList 将一组值,转换成list
        List<Integer> asList = Arrays.asList(2,3,4,5,6,1);
        System.out.println("asList=" + asList);
​
    }
}

 

Arrays类练习题

案例:自定义Book类,里面包含name和price,按price排序(从大到小)。要求使用两种方式排序 , 对对象的某个属性排序, 有一个 Book[] books = 3本书对象. 方式1:使用前面学习过的传递 实现Comparator接口匿名内部类,也称为定制排序。 方式2:让Book实现Comparable接口,完成排序。

package class_Arrays;
​
import java.util.Arrays;
import java.util.Comparator;
​
/*
    案例:自定义Book类,里面包含name和price,按price排序(从大到小)。要求使用两种方式排序 , 
    对对象的某个属性排序, 有一个 Book[] books = 3本书对象.
    方式1:使用前面学习过的传递 实现Comparator接口匿名内部类,也称为定制排序。
    方式2:让Book实现Comparable接口,完成排序。
​
 */
public class ClassWork01 {
​
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {
        Book[] books = {new Book("三体1",30.2),new Book("三体2",28.2),new Book("三体3",29.2)};
        System.out.println(Arrays.toString(books));
        System.out.println("=============================");
//      Arrays.sort(books, new Comparator() {
//          @Override
//          public int compare(Object o1, Object o2) {
//
//              Book b1 = (Book)o1;
//              Book b2 = (Book)o2;
//              if(b1.getPrice() > b2.getPrice()) {
//                  return 1;
//              }else if (b1.getPrice() < b2.getPrice()) {
//                  return -1;
//              }else {
//                  return 0;
//              }
//          }
//      });
        Arrays.sort(books);
        
        System.out.println(Arrays.toString(books));
    }
}
​
class Book implements Comparable<Book>{
    private String name;
    private double price;
    public Book(String name, double price) {
        super();
        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 + "]";
    }
    
    @Override
    public int compareTo(Book o) {
        if(this == o) {
            return 0;
        }
        if(!(o instanceof Book)) {
            return 0;
        }
        double price = ((Book)o).price;
        if(this.price > price ){
            return -1;
        } else if(this.price < price) {
            return 1;
        } else {
            return 0;
        }
    }
}

 

System

  1. exit 退出当前程序

  2. arraycopy :复制数组元素,比较适合底层调用,一般使用Arrays.copyOf完成复制数组. int[] src={1,2,3}; int[] dest = new int[3]; System.arraycopy(src, 0, dest, 0, 3);

  3. currentTimeMillens:返回当前时间距离1970-1-1 的毫秒数

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

import java.util.Arrays;
​
public class System_ {
​
    public static void main(String[] args) {
​
        // -
​
        // System.out.println("hello, world~~");
        // System.exit(0); //退出程序
        //
        // System.out.println("hello, world~~");
​
        // arraycopy :复制数组元素,比较适合底层调用,一般使用Arrays.copyOf完成复制数组.
        int[] src = { 1, 2, 3 }; //源数组
        int[] dest = new int[3];//目标数组
        //解读
        //1. src源数组
        //2. 0 从src 的哪个索引开始拷贝
        //3. dest 目标数组
        //4. 0 表示把元素拷贝 到 dest第几个索引后
        //5. 3 拷贝几个元素
        System.arraycopy(src, 1, dest, 1, 2);
        System.out.print(Arrays.toString(dest));
​
    }
}

  



 

posted @ 2020-12-22 19:45  奋斗的小范同学  阅读(169)  评论(0编辑  收藏  举报