API常用方法、数组高级操作(二分、冒泡、递归、快排、Arrays)

目录

API常用方法

API - Math

API-System

Object-toString

Object-equals

API-Objects

API-BigDecaimal

API-Integer-获得对象

Integer-自动拆装箱

Integer-类型转换

二分查找

冒泡排序

递归

快排

Arrays-数组工具类


API常用方法

了解什么事API?

API(Application Programming Interface) :应用程序接口, 简单来说就是Java帮我们已经写好的一些方法,我们直接拿来用就可以了

API常用的一些类

Math,System,Object,Objects,BigDecimal,基本类型包装类,数组高级操作,Arrays....

API - Math

概述: Math类包含执行基本数字运算的方法.

特点: 没有构造方法,方法都被static修饰,我们可以通过类名 . 的形式调用提供的成员方法

常用方法:

public static int abs(int a)返回参数的绝对值
public static double ceil(double a)向上取整(不是四舍五入)
public static double floor(double a)向下取整(不是四舍五入)
public static int round(float a)四舍五入
public static int max(int a,int b)返回两个参数中的较大值
public static int min(int a,int b)返回两个参数中的较小值
public static double pow(double a,double b)返回a的b次幂
public static double random(); 返回[0.0,1.0)之间的随机正数
public class Test {
        public static void main(String[] args) {
            //public static int abs(int a); 返回参数的绝对值
            System.out.println(Math.abs(-10));

            //public static double ceil(double a); 向上取整(不是四舍五入)
            System.out.println(Math.ceil(10.1)); //11.0
            System.out.println(Math.ceil(10.9)); //11.0

            //public static double floor(double a); 向下取整(不是四舍五入)
            System.out.println(Math.floor(10.1)); //10.0
            System.out.println(Math.floor(10.9));//10.0

            //public static int round(float a); 四舍五入
            System.out.println(Math.round(3.14)); //3
            System.out.println(Math.round(8.88)); //9

            //public static int max(int a,int b); 返回两个参数中的较大值
            System.out.println(Math.max(10,20)); //20
            //public static int min(int a,int b); 返回两个参数中的较小值
            System.out.println(Math.min(10,20)); //10

            //public static double pow(double a,double b); 返回a的b次幂
            System.out.println(Math.pow(2,2)); //4.0
            System.out.println(Math.pow(2,3)); //8.0

            //public static double random(); 返回[0.0,1.0)之间的随机正数
            System.out.println(Math.random()); //随机值
            System.out.println(Math.random()); //随机值
            System.out.println(Math.random()); //随机值
        }
    }  	       	

API-System

System类特点 : 没有构造方法,方法都被static修饰,我们可以通过类名点调用提供的成员方法

其中,Math或System的构造方法都被private私有

常用的方法:

public static void exit(int status)终止虚拟机,非零参数标表示异常停止
public static long currentTimeMillis()返回当前时间的毫秒值

public static void arraycopy(

数据源数组,起始索引,目的地数组,起始索引,拷贝个数)

数组元素拷贝
public class Test {
        public static void main(String[] args) {
            //public static void exit(int status); 终止虚拟机,非零参数标表示异常停止
    //        System.out.println("程序正在运行...");
    //        System.exit(0);
    //        System.out.println("看看我打印了吗...");

            //public static long currentTimeMillis(); 返回当前时间的毫秒值
            long start = System.currentTimeMillis();
            String s = "";
            for (int i = 0; i < 50000; i++) {
                s += i;
            }
            long end = System.currentTimeMillis();
            System.out.println("程序运行时间:" + (end - start));

            //arraycopy(数据源数组,起始索引,目的地数组,起始索引,拷贝个数); 数组元素copy
            int[] arr1 = {1, 2, 3, 4, 5};
            int[] arr2 = new int[10];
            //将arr1中所有元素拷贝到arr2中
    //        System.arraycopy(arr1,0,arr2,0,arr1.length);
            //查看数组元素
    //        System.out.println(Arrays.toString(arr2)); //[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]

            //将arr1中后两个,拷贝到arr2中的后两个位置
            System.arraycopy(arr1,3,arr2,8,2);
            //查看数组元素
            System.out.println(Arrays.toString(arr2)); //[0, 0, 0, 0, 0, 0, 0, 0, 4, 5]
        }
    }

Object-toString

Object概述:
    每个类都可以将Object作为父类, java中所有的类都直接或者间接的继承自Object

Object的构造方法:
    只有一个空参构造 public Object(){}

构造方法的特点: 如果我们不提供构造,系统会"提供一个默认的空参构造",就是从Object类中继承来的!

public class Test extends Object{ // 如果不指定父类,系统会发一个父类!
    public static void main(String[] args) {
        // 创建学生对象
        Student stu = new Student();
        //自定义学生类, 没有提供构造方法, 空参哪里来的? 继承Object来的
        // 打印对象名
//        System.out.println(stu); //com.itheima03_Object.Student@1e643faf

        //重写Student类的toString方法后,可以打印对象内容
        System.out.println(stu); //Student{name='null', age=0}

// 自定义学生类, 没有提供构造方法
class Student {
    private String name;
    private int 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 "Student{" +
//                "name='" + name + '\'' +
//                ", age=" + age +
//                '}';
//    }

    // 重写模板可以选择String或者StringBuilder
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Student{");
        sb.append("name='").append(name).append('\'');
        sb.append(", age=").append(age);
        sb.append('}');
        return sb.toString();
    }
}

Object-equals

public class Test {
    public static void main(String[] args) {
        // 创建两个对象
        Student s1 = new Student("张三",18);
        Student s2 = new Student("张三",18);

        // 比较两个对象
        System.out.println(s1 == s2); //false
//        System.out.println(s1.equals(s2)); //false?????

        // 重写Student中的equals方法再次比较
        System.out.println(s1.equals(s2)); //true

        /*
            1.我们调用s1的equals作比较,要去Student中找有没有equals方法?
            2.答案是没有的,那么就要去父类(Object)中找
            3.找到了,我们发现比较的是地址值!s1和s2都是new出来的所以比较地址是false
                public boolean equals(Object obj) {
                    return (this == obj);
                }
            4.如果比较s1和s2的内容,需要在Student中重写equals方法(快捷键)
         */
    }
}

// 自定义学生类
class Student extends Object{
    @Override
    public boolean equals(Object o) {
        // 如果地址一样,代表是同一个对象
        if (this == o) return true;
        // 如果地址不一样,再比较其他内容
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }
//    暂时用不到hashCode方法,可以删除调
//    @Override
//    public int hashCode() {
//        return Objects.hash(name, age);
//    }
    private String name;
    private int age;
    public Student() {}
    public Student(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() {
        final StringBuilder sb = new StringBuilder("Student{");
        sb.append("name='").append(name).append('\'');
        sb.append(", age=").append(age);
        sb.append('}');
        return sb.toString();
    }
}

Object-面试题

public class Object面试题{
    public static void main(String[] args) {
        // 创建相同内容的String对象和sb对象
        String s = "abc";
        StringBuilder sb = new StringBuilder(s);

        System.out.println(s.equals(sb));  //false 因为sb不是String对象
        /*
            当前调用的是String类的equals方法,跟源码:
                public boolean equals(Object anObject) {
                    //1.先比较地址值
                    if (this == anObject) {
                        return true;
                    }
                    //2.如果地址不一样,先通过instanceof关键字判断传递的参数,是不是String对象
                    if (anObject instanceof String) {
                        String aString = (String)anObject;
                        if (coder() == aString.coder()) {
                        return isLatin1() ? StringLatin1.equals(value, aString.value)
                                          : StringUTF16.equals(value, aString.value);
                        }
                    }
                    //3.如果不是String对象直接返回false
                    return false;
                }
         */
        System.out.println(sb.equals(s)); //false 因为在比较地址值
        /*
            当前调用的是StringBuilder的equals方法,跟源码:
                发现StringBuilder类没有提供自己的equals方法
                所以就代表使用的是Object的equals方法,我们之前讲过Object的equals比较的是地址值
                    public boolean equals(Object obj) {
                        return (this == obj);
                    }
                所以s和sb是两个地址,返回false
         */
    }
}

API-Objects

常用方法:

public static String toString(对象)返回对象的字符串表示形式
public static String toString(对象,默认字符串)返回对象的字符串表示形式(如果对象为null,返回第二个参数)
public static Boolean isNull(对象)判断对象是否为空
public static Boolean nonNull (对象)判断对象是否不为空

代码示例:

public class Test {
        public static void main(String[] args) {
            //public static String toString(对象); 返回对象的字符串表示形式
    //        Student s = new Student("张三",18);
    //        System.out.println(Objects.toString(s)); //相当于调用Student类中的toString方法
    //        System.out.println(s);

            //public static String toString(对象,默认字符串); 
            //返回对象的字符串表示形式(如果对象为null,返回第二个参数)
            Student s = new Student("张三",18);
            s = null;
            System.out.println(Objects.toString(s,"对象为空!"));

            //public static Boolean isNull(对象); 判断对象是否为空
            Student s1 = new Student("张三",18);
            System.out.println(Objects.isNull(s1)); //false

            //public static Boolean nonNull (对象); 判断对象是否不为空
            Student s2 = new Student("张三",18);
            System.out.println(Objects.nonNull(s2)); //true
        }
    }

    // 自定义学生类
    class Student{
        @Override
        public String toString() {
            System.out.println("看看我执行了吗?");
            final StringBuilder sb = new StringBuilder("Student{");
            sb.append("name='").append(name).append('\'');
            sb.append(", age=").append(age);
            sb.append('}');
            return sb.toString();
        }
        private String name;
        private int age;
        public Student() {}
        public Student(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;}
    }

API-BigDecaimal

计算机中存在进制的转换:
    10进制 -> (转2进制时数据丢失,会用一个无限接近的2进制来表示)2进制 -> 10进制

BigDecimal类概述?
    可以做精确计算

BigDecimal构造方法:
    BigDecimal b = new BigDecimal(数值型数据);
    BigDecimal b = new BigDecimal(字符串); //推荐使用

四则运算:

public BigDecimal add(另一个BigDecimal对象)
public BigDecimal subtract(另一个BigDecimal对象)
public BigDecimal multiply(另一个BigDecimal对象)
public BigDecimal divide(另一个BigDecimal对象)

特殊方法:

        如果使用BigDecimal的除法运算, 当结果除不尽时, 需要使用divide的重载函数(重载方法)
            public BigDecimal divide(另一个BigDecimal对象,保留位数,舍入模式);

public static void main(String[] args) {
            //创建对象
            BigDecimal b1 = new BigDecimal("0.3");
            BigDecimal b2 = new BigDecimal("4"); //0.3除以4=0.075

            //public BigDecimal divide(另一个BigDecimal对象,保留位数,舍入模式);
                                //进一法 BigDecimal.ROUND_UP
                                //去尾法 BigDecimal.ROUND_FLOOR
                                //四舍五入 BigDecimal.ROUND_HALF_UP
            System.out.println(b1.divide(b2,2,BigDecimal.ROUND_UP)); //0.08
            System.out.println(b1.divide(b2,2,BigDecimal.ROUND_FLOOR)); //0.07
            System.out.println(b1.divide(b2,2,BigDecimal.ROUND_HALF_UP)); //0.08
        }

基本数据类型包装类

包装类?
             将基本类型封装成对象, 好处是可给对象同提供更多的功能(方法)来操作数据

包装类常用操作?
            用于聚类数据类型与字符串之间的转换("100" -> 100)

四类八种对应的包装类: int和char有点特殊,其余都是首字母大写
    byte
    short
    int -> Integer
    long
    float
    double
    char -> Character
    boolean

//打印int的取值范围
    System.out.println(Integer.MIN_VALUE); //-2147483648
    System.out.println(Integer.MAX_VALUE); //2147483647

API-Integer-获得对象

Integer包装了一个基本类型数据int的值, 构造方法有两种(了解), 我们使用静态方法valueOf代替(推荐)

public static void main(String[] args) {
            //构造方法(过时)
            Integer i1 = new Integer(100);
            Integer i2 = new Integer("100"); 

            System.out.println(i1); //100
            System.out.println(i2); //100

            //静态方法valueOf(推荐)
            Integer i3 = Integer.valueOf(200);
            Integer i4 = Integer.valueOf("200");

            System.out.println(i3); //200
            System.out.println(i4); //200
        }

Integer-自动拆装箱

    什么是自动拆装箱?
            自动装箱: 基本类型转为对应的包装类

                        //自动装箱: 基本类型转为对应的包装类
                           Integer i1 = 100;
            自动拆箱: 包装类转为对应的基本类型

                        //自动拆箱: 包装类转为对应的基本类型
                            int i = i1;

Integer-类型转换

int和String的转换?
    1. int -> String:
                        public static String valueOf(int i);      //将int装为String
    2. String -> int:
                        public static int parseInt(String s);     // 将String装为int

public static void main(String[] args) {
            int i = 200;
            String s = "100";
            System.out.println(s + i); //100200 这是字符串的拼接

            //int -> String: 加双引号(字符串拼接)
            String s1 = i + "";
            System.out.println(s1); //200
            
            //int -> String: public static String valueOf(int i); 将int转为String
            String s2 = s.valueOf(i);
            System.out.println(s2); //200

            //String -> int: public static int parseInt(String s); 将String装为int
            int ii = Integer.parseInt("666");
            System.out.println(ii); //666 整数类型
        }

 二分查找

二分查找思路:
    1. 定义两个变量表示查找范围, 默认min=0, max=最大索引
    2. 循环查找, min<=max是循环继续条件
    3. 计算mid的值
    4. 判断mid指向的元素是不是目标元素, 如果是直接返回对应索引
    5. 如果目标元素在mid的左半边, min不变, max = mid - 1, 继续循环查找
    6. 如果目标元素在mid的右半边, max不变, min = mid + 1, 继续循环

public static void main(String[] args) {
        // 生成数组
        int[] arr = {1,2,3,4,5};

        // 测试方法
        System.out.println(myBinarySearch(arr, 4)); //3
        System.out.println(myBinarySearch(arr, 20)); //-1
    }

    // 二分查找
    public static int myBinarySearch(int[] arr, int num) {
        //1. 定义两个变量表示查找范围, 默认min=0, max=最大索引
        int min = 0;
        int max = arr.length - 1;
        //2. 循环查找, min<=max是循环继续条件
        while (min <= max) {
            //3. 计算mid的值
            //int mid = (min + max) / 2;
            int mid = (min + max) >> 2; //右移1位等于除以2,效率更高
            //4. 判断mid指向的元素是不是目标元素, 如果是直接返回对应索引
            if (arr[mid] == num) {
                return mid;
            } else if (num < arr[mid]) {
                //5. 如果目标元素在mid的左半边, min不变, max = mid - 1, 继续循环查找
                max = mid - 1;
            } else if (num > arr[mid]) {
                //6. 如果目标元素在mid的右半边, max不变, min = mid + 1, 继续循环查找
                min = mid + 1;
            }
        }
        //7. 上述都不满足, 返回-1
        return -1;
    }

冒泡排序

冒泡排序思路:
    如果有n个元素比, 总共需要比n-1次
    遍历数组, 前后两个元素比较, 大的放左边(数据交换), 防止索引越界, 需要让长度-1
    每一次比较完毕, 下一次的比较会少一个数组参与

public static void main(String[] args) {
        // 定义数组
        int[] arr = {5, 3, 1, 4, 2};
        // 如果有n个元素比, 总共需要比n-1次
        for (int i = 0; i < arr.length - 1; i++) {
            // 遍历数组, 前后两个元素比较, 大的放左边(数据交换), 防止索引越界, 需要让长度-1
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
            //查看每一次比较的结果
            //System.out.println(Arrays.toString(arr));
        }
        System.out.println(Arrays.toString(arr));


//        // 每一次比较完毕, 下一次的比较会少一个数组参与
//        for (int i = 0; i < arr.length - 1 - 1; i++) {
//            if (arr[i] > arr[i + 1]) {
//                int temp = arr[i];
//                arr[i] = arr[i + 1];
//                arr[i + 1] = temp;
//            }
//        }
//        System.out.println(Arrays.toString(arr));
//
//        // 每一次比较完毕, 下一次的比较会少一个数组参与
//        for (int i = 0; i < arr.length - 1 - 2; i++) {
//            if (arr[i] > arr[i + 1]) {
//                int temp = arr[i];
//                arr[i] = arr[i + 1];
//                arr[i + 1] = temp;
//            }
//        }
//        System.out.println(Arrays.toString(arr));
//
//        // 每一次比较完毕, 下一次的比较会少一个数组参与
//        for (int i = 0; i < arr.length - 1 - 3; i++) {
//            if (arr[i] > arr[i + 1]) {
//                int temp = arr[i];
//                arr[i] = arr[i + 1];
//                arr[i + 1] = temp;
//            }
//        }
//        System.out.println(Arrays.toString(arr));

    }

递归

递归概述: 从程序角度来说, 递归就是在方法中调用自己的现象

递归思路: 将复杂问题简单, 使用少量的程序就可描述出解题过程所需的多次重复计算

递归要找的两个核心:
    核心1.递归出口: 否则出现内存溢出(栈内存中的方法装不下了!)
    核心2.递归规则: 与原问题相似的, 但是规模较小的问题

public static void main(String[] args) {
        int sum = getSun(100);
        System.out.println(sum); //5050
    }

    public static int getSun(int i) {
        // 递归出口
        if(i == 1){
            return 1;
        }else{
            /*
                1-100的和
                 100+(1-99的和)
                   99+(1-98的和)
                    98+(1-97的和)
                     ... 以此类推
                       1
             */
            // 递归规则
            return i + getSun(i - 1);
        }
    }

 快排

冒泡排序: 一次循环结束, 找到最大元素的位置. 每一次循环结束, 都会少一个数字参与下一次循环
    
快速排序: 一次循环结束, 找到基准数的位置 (基准数: 每一次递归第一个数字为基准数)
    比基准数小的, 放在右边; 比基准数大的, 放在左边 (顺序不管)
    知道两个指针重叠, 这时基准数归位 (基准数归位: 将基准数与当前位置的数据交换)
         
快排思路:
    1.从右边开始找比基准数小的
    2.从左边开始找比基准数大的
    3.交换两个位置上的数字
    4.开始指针继续朝右找, 结束指针继续向左找, 直到重叠
    5.基准数归位

public static void main(String[] args) {
            // 定义数组
            int[] arr = {6, 1, 2, 7, 9, 3, 4, 5, 8, 10};

            // 测试方法
            arraySort(arr, 0, arr.length - 1);

            // 打印结果
            System.out.println(Arrays.toString(arr));
        }

        private static void arraySort(int[] arr, int left, int right) {
            // [1]递归出口: 当left大于right时, 递归结束
            if(left > right){
                return;
            }

            // 每次循环后, 还要使用初始索引, 做零时存储
            int left0 = left;
            int right0 = right;

            // 定义基准数, 数组左边第一个数字
            int baseNumber = arr[left0];

            // 循环查找, 如果指针没重叠就继续
            while (left != right) {
                // 从右边开始找比基准数小的: 当前的元素大于基准数, 并且两个指针没有相遇
                while (arr[right] >= baseNumber && right > left) {
                    //  就继续找
                    right--;
                }
                // 从左边开始找比基准数大的: 当前的元素小于基准数, 并且两个指针没有相遇
                while (arr[left] <= baseNumber && right > left) {
                    left++;
                }
                // 上述循环都结束, 交换两个位置上的数字
                int temp = arr[left];
                arr[left] = arr[right];
                arr[right] = temp;
            }

            // 当left等于right时, 上述循环结束, 基准数归位置
            int temp = arr[left];
            arr[left] = arr[left0]; //基准数: 数组左边第一个数字(arr[left0])
            arr[left0] = temp;

            // [2]递归规则: 再次调用方法时, 只需要修改查找范围
            // 基准数左边
            arraySort(arr,left0,left - 1); //(数组, 零时最小索引, 基准数索引-1)
            // 基准数右边
            arraySort(arr,left + 1,right0); //(数组, 基准数索引+1, 零时最大索引)
        }

Arrays-数组工具类

数组工具类Arrays:
    构造方法使用private修饰, 不能创建对象
    方法都被static修饰, 通过类名直接调用

Arrays常用方法:
    public static String toString(int[] arr); 返回指定数组的字符串表示
    public static void sort(int[] arr); 按照数字顺序排列指定数组元素
    public static binarySearch(int[] arr,int key); 利用二分查找返回指定元素的索引, 不存在返回插入点-1

public static void main(String[] args) {
            //定义数组
            int[] arr = {5, 2, 4, 1, 3};
            
            //public static String toString(int[] arr); 返回指定数组的字符串表示
            System.out.println(Arrays.toString(arr));

            //public static void sort(int[] arr); 按照数字顺序排列指定数组元素
            Arrays.sort(arr);
            System.out.println(Arrays.toString(arr));

            //public static binarySearch(int[] arr,int key); 利用二分查找返回指定元素的索引, 不存在返回插入点-1
            int index = Arrays.binarySearch(arr, 5);
            if (index == -1) {
                System.out.println("元素不存在");
            } else {
                System.out.println("元素在数组中索引为:" + index);
            }
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值