Java常用核心类库使用方法总结

核心类库的简单使用

Objects类

Objects类包含实用程序方法,用于操作对象或操作对象前检查某些条件。

常用方法

  1. check方法
    • checkFromIndexSize(int fromIndex, int size, int length)查是否在子范围从fromIndex (包括)到fromIndex + size (不包括)是范围界限内0 (包括)到length (不包括)。在范围内返回fromIndex,不在范围内抛出IndexOutOfBoundsException。
    • checkFromToIndex(int fromIndex, int toIndex, int length)检查是否在子范围从 fromIndex (包括)到 toIndex (不包括)是范围界限内 0 (包括)到 length (不包括)。在范围内返回fromIndex,不在范围内抛出IndexOutOfBoundsException.
  2. equals方法
    • equals(Object a, Object b) 比较两个对象的值是否相等,String和StringBuilder即使存储的信息一样也不相等。
  3. hashCode方法
    • hashCode(Object o) 返回对象的哈希码,对象的内存地址不同,哈希码就不同
  4. isNull方法
    • isNull(Object obj) 如果对象是null,返回true;调用空参构造器创建对象,该对象也不是null,其属性可能为null。
  5. nonNull方法
    • nonNull(Object obj) 如果对象是非空,返回true;与isNull方法相反
  6. requireNonNull方法
    • requireNonNull(T obj) 检查指定对象的引用是否为空,如果不为空,将对象返回,如果为空抛出NullPointerException
  7. toString方法
    • toString(Object o) 用字符串打印指定对象信息
  8. compare方法
  • .compare(T a, T b, Comparator<? super T> c)比较两个对象;相等返回0,大于返回1,小于返回0
public static void main(String[] args) {
        //1.check方法
        int a = Objects.checkFromIndexSize(6, 4, 10);
        int b = Objects.checkFromToIndex(6,8,10);
        System.out.println(a); //打印6
        System.out.println(b); //打印6
    
        //2.equals方法
        String s1 = "123";
        String s2 = "123";
        String s3 = "1234";
        System.out.println(Objects.equals(s1, s3)); //返回false
   	    System.out.println(Objects.equals(s1, s2)); //返回true
        System.out.println(Objects.equals(s1, s4)); //返回false
    
    
        //3.hashcode()方法
        System.out.println("3---------------------");
        System.out.println(Objects.hashCode(s1)); //48690
        System.out.println(Objects.hashCode(s2)); //48690	
        System.out.println(Objects.hashCode(s3)); //1509442
    
        //4.isNull()方法
        System.out.println("4-------------------");
        StringBuffer sb = new StringBuffer();
        Student stu = new Student();
        String s ="";
        System.out.println(Objects.isNull(sb));	//false
        System.out.println(Objects.isNull(s1));	//false
        System.out.println(Objects.isNull(s)); //false
        System.out.println(Objects.isNull(stu.getAge())); 	//true
    
    
        //5.nonNull方法
        System.out.println("5-----------------------");
        System.out.println(Objects.nonNull(sb)); //true
        System.out.println(Objects.nonNull(stu.getName())); //false
    
        //6.requireNonNull方法
        System.out.println("6----------------------");
        Integer i = 33643;
        System.out.println(Objects.requireNonNull(s1,"s1 must not be null")); //打印123
        System.out.println(Objects.requireNonNull(i)); //打印33643
        System.out.println(Objects.requireNonNull(stu)); // 打印Student{name='null', age='null', classNum='null'}
    
        //7.toString方法
        System.out.println("7--------------------");
        System.out.println(Objects.toString(stu)); //打印Student{name='null', age='null', classNum='null'}
    	
		//8.compare方法
    	System.out.println(Objects.compare(s3,s2,new Comparator(){
            @Override
            public int compare(Object o1, Object o2) {
                String s1 = null;
                String s2 = null;
                if (o1 instanceof String){
                    s1 = (String)o1;
                }
                if (o2 instanceof String){
                     s2 = (String)o2;
                }
                int result = s1.compareTo(s2);
                return result;
            }
        })); //返回1

    }

Math类

Math类包含执行基本数字运算的方法,所有的方法都是static,且Math类无法创建实例化对象

public class MathTest {
    public static void main(String[] args) {
        //0.Math.E(获取自然对数)Math.PI(获取圆周率)
        //1.abs():对各种数据类型求绝对值(double,float,int,long)
        System.out.println(Math.abs(-2.8)); //2.8
        System.out.println(Math.abs(-3)); //3
        System.out.println(Math.abs(10)); //10
        //2.三角函数与反三角函数
        //asin():求反正弦值
        //acos():求反余弦值
        //atan():求反正切值
        //sin():求正弦值,用弧度
        //cos():求余弦值,用弧度
        //tan():求正切值,用弧度
        //atan2(y,x):求向量(x,y)与x轴的夹角大小
        System.out.println("2--------------------");
        System.out.println(Math.acos(-1)); // PI
        System.out.println(Math.asin(1)); // PI/2
        System.out.println(Math.atan(1)); // PI/4
        System.out.println(Math.sin(Math.PI/2)); // 1.0
        System.out.println(Math.cos(Math.PI)); // -1.0
        System.out.println(Math.tan(Math.PI/4)); // 1
        System.out.println(Math.atan2(1,1)); // PI/4
        //3.开根号
        //sqrt():开平方
        //cbrt():开立方
        //hypot(x,y):求x和y到原点的距离; 以上返回类型均为double
        System.out.println("3------------");
        System.out.println(Math.sqrt(4)); // 2
        System.out.println(Math.cbrt(8)); // 2
        System.out.println(Math.hypot(3,4)); // 5
        //4.最值:
        //max():返回两个数相比的最大值
        //min():返回两个数相比的最小值
        System.out.println("4---------------");
        System.out.println(Math.max(8.5,10.1)); //10.1
        System.out.println(Math.min(6,9)); // 6
        //5.求对数:只能传递double类型的参数
        //log(a):求a的自然对数(以e为底)
        //log10(a):求a的自然对数(以10为底)
        //log1p(a):求a+1的自然对数(以e为底)
        System.out.println("5---------------");
        System.out.println(Math.log(Math.E)); //1
        System.out.println(Math.log10(10)); // 1
        System.out.println(Math.log1p(Math.E-1)); // 1 
        //6.求幂:传递double类型参数
        //exp(a):求e的a次方
        //expm1(a):求e的a次方-1
        //pow(x,y):求x的y次方
        System.out.println("6--------------");
        System.out.println(Math.exp(0)); // 1
        System.out.println(Math.expm1(0)); // 0
        System.out.println(Math.pow(2,3)); // 8
        //7.random():求0(包括)到1(不包括)的随机数
        System.out.println("7----------------");
        //生成0到100的随机数
        System.out.println(Math.random()*100);
        //8.转换
        //toDegrees():弧度转化为角度
        //toRadians():角度转化为弧度
        System.out.println("8------------------");
        System.out.println(Math.toDegrees(Math.PI/4));// 45
        System.out.println(Math.toRadians(180));// PI
        //9.其他
        //addExact(x,y):求参数x和y的和
        System.out.println("9-----------------");
        System.out.println(Math.addExact(4,5));// 9
        //ceil():向上取整(double)
        System.out.println(Math.ceil(1.2)); // 2 
        //floor():向下取整(double)
        System.out.println(Math.floor(1.8)); // 1
        //round():四舍五入
        System.out.println(Math.round(1.5));// 2
        //rint(a):返回最接近a的double值
        System.out.println(Math.rint(3.1));// 3 
        System.out.println(Math.rint(3.9));// 4 
        //copySign(x,y) 返回 用y的符号取代x的符号后新的x值
        System.out.println(Math.copySign(1,-2)); // -1
        //nextUp(a):比a大一点点的浮点数
        //nextDown(a):比a小一点点的浮点数
        System.out.println(Math.nextUp(5)); // 5.000005
        System.out.println(Math.nextDown(5));// 4.9999995
    }
}

Arrays类

该类包含用于操作数组的各种方法(例如排序和搜索)。 此类还包含一个静态工厂,允许将数组视为列表

public class ArraysTest {
    public static void main(String[] args) {
        //1.asList(T...a):返回由指定数组支持的固定大小列表
        //注意:这个方法返回的不是Java.util.Arraylist,而是一个Arrays的内部类Java.util.Arrays.ArraysList.
        String[] arr = {"1","张三","18"};
        int[] nums = {2,4,1,5,3};
        //1.1返回的list只能进行查看和修改,list长度是固定的,不能进行添加和删除,否则会抛出UnsupportedOperationException			异常
        //1.2返回的列表ArrayList里面的元素都是引用,不是独立出来的对象.
        //1.3 Arrays.asList 比较适合那些已经有数组数据或者一些元素,而需要快速构建一个List,只用于读取操作,而不进行添加或删				除操作的场景。
        //1.4 生成的列表可以调用toArray()方法才变成数组
        List<String> stringList = Arrays.asList(arr);
        List<int[]> ints = Arrays.asList(nums);
        stringList.set(0,"0");
        System.out.println(stringList.size());//3
        System.out.println(ints.size());//1
        System.out.println(stringList);//[0, 张三, 18]
        Object[] objects = stringList.toArray();
        /*
        *stringList.add("a");
        *stringList.remove(1);
        * 以上两个操作都会抛出异常
        */

        //2.binarySearch():用二分法查找数组中的某个元素,可以指定查找范围(数组的起始位置),找到后返回元素下标,否则返回-1
        //注意:二分查找是对有序数组才行,故可以先要用Arrays.sort()方法对数组进行排序,在调用此方法查找。
        //3.sort():将指定数组按升序排序。
        //以上两个方法的参数包括7种基本数据类型(byte,short,int,long,float,double,char)
        //还包括Object类型(实现Comparable接口)和比较器(Comparator)
        System.out.println("----------------------");
        Arrays.sort(nums);
        for (int num:nums) {
            System.out.print(num + " ");// 1 2 3 4 5
        }
        System.out.println();
        int index = Arrays.binarySearch(nums, 4);
        System.out.println(index);// 3

        //4.copyOf(original,newLength):复制指定类型数组,指定新数组长度,返回的数组拷贝了源数组元素
        //4.1 copyOfRange(original,from,to):将指定数组的指定范围复制到新数组种
        System.out.println("-----------copyOf--------------");
        int[] nums2 = Arrays.copyOf(nums, 3);
        for (int number: nums2) {
            System.out.print(number+" ");//1 2 3 
        }
        System.out.println();

        //5.compare():按顺序比较两个数组元素,可以指定起始位置
        //先比较数组的长度,返回前后者数组长度之差,如果长度一样,依次比较每个元素大小,前者大返回1,前置小返回-1,全部一样返回0
        System.out.println("----------compare----------");
        System.out.println(Arrays.compare(nums,nums2)); //2  
        System.out.println(Arrays.compare(nums,0,2,nums2,0,2));// 0
        int[] nums1 = {2,2,3,4,5};
        System.out.println(Arrays.compare(nums1,nums));//1 

        //6.equals():比较两个一维数组的内容是否相等,相等返回true
        //deepEquals():如果两个指定数组的彼此深度相等则返回true,适合多维数组的比较。
        System.out.println("-----------equals----------");
        System.out.println(Arrays.equals(nums,0,2,nums2,0,2));// true
        System.out.println(Arrays.equals(nums1,nums2));// false

        //7.fill([],val):可以给指定数组赋值val,也可以在指定范围内赋值
        System.out.println("-----------fill--------------");
        int[] nums3 = new int[5];
        Arrays.fill(nums3,10);
        for (int num: nums3) {
            System.out.print(num+" ");// 10 10 10 10 10
        }
        System.out.println();

        //8.toString()和deepToString():分别用来打印用来打印一维数组的元素和多层次嵌套的数组元素
        System.out.println("--------toString--------");
        System.out.println(Arrays.toString(nums));//1 2 3 4 5 
        String s = Arrays.toString(arr);
        System.out.println(s);//[0, 张三, 18]


        //9.mismatch():查找并返回两个数组之前第一次不匹配的索引
        System.out.println("-------mismatch---------");
        System.out.println(Arrays.mismatch(nums,nums1));// 0

        //其他
        //parallelPrefix():使用提供的函数并行地累积给定数组的每个元素。
        //parallelSetAll():使用提供的生成器函数并行设置指定数组的所有元素以计算每个元素。
        //stream():将数组转为流式,对array进行流式处理,可用一切流式处理的方法
        //spliterator():返回一个Spliterator,进行Spliterator相关操作
    }
}

BigDecimal类

为了实现精确运算,得到精度准确的结果

public class BigDecimalTest {
    public static void main(String[] args) {
        double a1 = 0.8;
        double a2 = 1.6;
        //1.BigDecimal():该构造方法可以传递不同的数值对象参数来创建BigDecimal对象
        BigDecimal b1 = new BigDecimal("0.8");
        BigDecimal b2 = new BigDecimal("1.6");
        BigDecimal b3 = new BigDecimal(1.6);
        //参数类型为double的构造方法的结果有一定的不可预知性,因为由于浮点数本身的精度问题,传进来的数值不一定是我们所见的准确值,会产生精度丢失。
        //而参数为String()的构造方法是完全可以预知的,建议优先使用。
        System.out.println("b2 values is " + b2);// b2 values is 1.6 
        System.out.println("b3 values is " + b3);// b3 values is 1.60000000000000008881784
        //通过BigDecimal对象调用算术运算方法得到结果是准确的,不会有精度丢失
        System.out.println(a1+a2); //2.4000000000000004 
        //2.1 加法
        BigDecimal sum = b1.add(b2); 
        System.out.println(sum.toString());//2.4
        //2.2 减法
        BigDecimal sub = b2.subtract(b1);
        System.out.println(a2-a1);//0.8
        System.out.println(sub);//0.8
        //2.3 乘法
        BigDecimal mul = b2.multiply(b1);
        System.out.println(a1*a2);//1.2800000000000002
        System.out.println(mul);//1.28
        //2.4 除法
        BigDecimal div = b2.divide(b1);
        System.out.println(a2/a1);//2.0
        System.out.println(div);//2	
        //2.5 计算次方
        BigDecimal pow = b1.pow(2);
        System.out.println(Math.pow(a1,2));//0.6400000000000001
        System.out.println(pow);//0.64


        //3.1 doubleValue():将BigDecimal对象转换为 double。
        double d = b2.doubleValue();
        System.out.println(d);//1.6
        //3.2 floatValue():将BigDecimal对象转换为 float
        float f = b2.floatValue();
        System.out.println(f);//1.6
        //3.3 longValue():将BigDecimal对象转换为 long
        //longValueExact():将此 BigDecimal转换为 long,检查是否丢失了信息,如丢失信息抛出ArithmeticException
        long l = b2.longValue();
        System.out.println(l);// 1
        //3.4 intValue():将BigDecimal对象转换为 int
        //intValueExact():将 BigDecimal转换为 int,检查是否丢失了信息,如丢失信息抛出ArithmeticException
        int i = b2.intValue();
        System.out.println(i);// 1

        //4.valueOf(): 转换一个double或long变成BigDecimal
        BigDecimal a3 = BigDecimal.valueOf(a1);
        System.out.println(a3); //0.8
        //5.compareTo大小比较():大于返回1,等于返回0,小于返回-1
        System.out.println(b1.compareTo(b2)); //-1
        //6.divideToIntegralValue(BigDecimal divisor):返回BigDecimal其值是(this/divisor)舍入的商(this/divisor)的整数部分
        System.out.println(b1.divideToIntegralValue(b2)); //0
        //7.remainder(BigDecimal divisor):返回 BigDecimal其值为(this % divisor) 。
        System.out.println(b1.remainder(b2)); //0.8
        //8.setScale():设置BigDecimal对象保留几位小数
        System.out.println(a3.setScale(2)); //0.80
        //其他:round():四舍五入
        //equals():判断BigDecimal两个对象是否相对
        //hashCode():计算BigDecimal的哈希码
    }
}

Date类

Date类表示特定的瞬间,精确到毫秒,使用Date类来表示当前系统时间

public class DateTest {
    public static void main(String[] args) {
        //1.调用Date的无参构造器,得到系统当前日期时间
        Date date = new Date();
        System.out.println(date); //Sun Feb 28 23:13:39 GMT+08:00 2021
        //2.调用Date(long date)构造方法,得到一个自1970年1月1日0点以来,加上参数date毫秒值的一个时间日期
        Date date2 = new Date(10000000000L);
        System.out.println(date2); //Mon Apr 27 01:46:40 GMT+08:00 1970
        //3.after(Date when):测试此日期是否在指定日期之后
        //before(Date when): 测试此日期是否在指定日期之前
        System.out.println(date.after(date2)); //true
        System.out.println(date.before(date2)); //false
        //4.getTime():返回日期所对应的毫秒值(自1970年1月1日00:00:00之后)
        //setTime(long time):将此 Date对象设置为表示格林尼治标准时间1970年1月1日00:00:00之后的time毫秒的时间点。
        System.out.println(date.getTime()); //1614525219401
        date.setTime(20000000000L);
        System.out.println(date.getTime());//20000000000
    }
}

DateFormat类

DateFormat是日期时间格式化子类的抽象类,它以语言无关的方式格式化和分析日期或时间

DateFormat要通过其子类SimpleDateFormat来创建对象

public class DateFormatTest {
    public static void main(String[] args) {
        //1.public SimpleDateFormat(String pattern):按照指定格式进行日期格式化
        Date date = new Date();
        //2.将Date对象转换为日期的字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        String time = sdf.format(date);
        System.out.println(time); //2021-02-28  23:21:03
        //3.将指定日期字符串转换为Date对象
        String s ="2001年12月27日";
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
        try {
            Date date1 = sdf2.parse(s);
            System.out.println(date1); //Thu Dec 27 00:00:00 GMT+08:00 2001
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //4.返回此日期格式模式的字符串
        System.out.println(sdf.toPattern());//yyyy-MM-dd  HH:mm:ss
    }
}

System类

System类包含几个有用的类字段和方法

//字段:
System.in //标准输入流
System.out //标准输出流
//方法:
System.gc() //垃圾回收器
System.exit(int n) //n=0,正常终止程序;n非0,异常终止程序
System.currentTimeMillis() //以毫秒为单位返回当前时间
System.arraycopy(Object src, int scrPos, Object dest, int destPos, int length) //将原数组从指定位置复制到目标数组的指定位置

String类

​ String类表示字符串,Java程序中所有的字符串文字(例如"abc")都为此类的实例。

特点

  1. String类是被fianl关键字修饰,一经创建就无法修改。
  2. 字符串缓冲区支持可变字符串,因为String类是不可变的,所以可以共享它们。
  3. String实例的值是通过字符数组实现字符串存储的。

String类是Java语言的核心类,提供了字符串的比较、查找、截取、大小转换等操作。

public class StringTest {
    @SuppressWarnings("all")
    public static void main(String[] args) {
        //一.获取
        //1.String的常用构造方法
        String s = "abcdefg";
        String str = new String("abcdefg");
        System.out.println(s == str); //false
        
        //2.charAt(int index):返回指定索引出的char值
        System.out.println(s.charAt(1)); //b 
        System.out.println(str.charAt(1)); //b
        
        //3.int length():返回字符串的长度
        System.out.println(s.length()); //7
        
        //4.indexOf():返回指定字符在字符串第一次出现的索引
        //4+.lastIndexOf():返回指定字符串最后一次出现在该字符串中的索引
        System.out.println(s.indexOf("c"));//2
        //可以加入第二个参数从fromindex开始搜索
        System.out.println(s.indexOf("c",1));//2
        
        //二.判断
        //5.contains(CharSequence s):判断某字符串是否包含指定的char值序列时,如果有则返回true;
        System.out.println(s.contains("d")); //true
        System.out.println(s.contains("D")); //false
        
        //6.compareTo:按字典顺序比较两个字符串
        //如果此字符串按字典顺序小于字符串参数,则小于0; 如果此字符串按字典顺序大于字符串参数,则值大于0;两个字符串相等返回0
        System.out.println("---------6--------------");
        System.out.println(s.compareTo(str));//0
        String s1 = "gfedcba";
        System.out.println(s.compareTo(s1)); //-6
        
        //7.isEmpty():判断字符串长度是否为0;如果为0,返回true。
        System.out.println(s.isEmpty());//false
        String s2 = "";
        System.out.println(s2.isEmpty());//true
        
        //8.startsWith()/endWith():判断指定字符串是否以指定字符内容开头或结尾
        System.out.println("-------8-------");
        System.out.println(s.startsWith("a")); //true
        System.out.println(s.endsWith("g")); //true
        
        //9.equals():判断俩字符串的内容是否相等
        //equalsIgnoreCase(String anotherString):忽略字母大小写,判断字符串内容是否相等
        String s3 = "ABCDEFG";
        System.out.println("--------9----------");
        System.out.println(s.equals(str));//true
        System.out.println(s.equals(s1));//false
        System.out.println(s.equalsIgnoreCase(s3));//true
        
        //三.转换
        //10.构造方法 String(char []): 将字符数组转换为字符串
        //String(byte[] bytes):将字节数组转换为字符串
        char[] c1 = {'1','2','3','4',};
        String s4 = new String(c1);
        System.out.println(s4); //1234
        
        //11.valueOf():将传进来的参数转换为字符串的表示形式(静态方法),可以是基本数据类型类型或引用数组
        String s5 = String.valueOf(c1);
        System.out.println(s4.equals(s5)); //true
        System.out.println(s5);//
        System.out.println(String.valueOf(24.8)); //24.8
        
        //12.toLowerCase():将字符串里面的小写字母变成大写字母
        //toUpperCase():将字符串里面的大写字母变成小写字母
        String str1 = "Hello World";
        System.out.println(s.toUpperCase()); //ABCDEFG
        System.out.println(str1.toLowerCase()); //hello world
        
        //13.toCharArray():将字符串转换为新的字符数组
        char[] chars = s5.toCharArray(); 
        
        //14.getByte():使用平台的默认字符集将此String编码为字节序列,将结果存储到新的字节数组中。
        byte[] bytes = s4.getBytes();
        
        //四、替换
        //15.replace(char oldChar, char newChar):用newChar替换字符串中出现oldChar的位置,再返回一个新的字符串
        String str2 = str1.replace( ' ', '-');
        System.out.println(str2);//hello-world
        
        //16.replaceAll(String s1, String s2):将所有出现s1的内容转换为s2
        System.out.println(str1.replaceAll("ll","o")); //Heoo World
        
        //17.replaceFirst(String s1, String s2):将字符串中第一次出现s1的内容转换为s2
        System.out.println(str1.replaceFirst("l","d")); //Hedlo World
        
        //五.切割
        //18.trim():去掉字符串中的左右空格
        String str3 =" Hello World! ";
        System.out.println(str3.trim());//Hello World!(无左右空格了)
        
        //19.split(String regex):根据给定的正则表达式的匹配来拆分此字符串。形成一个新的String数组。
        String[] s6 = str3.split(" ");
        System.out.println(s6.length);//3
        System.out.println(s6[1]);//Hello
        
        //20.substring(int beginIndex,int endIndex):截取字符串,包括beginIndex位置的,不包括endIndex位置的
        System.out.println(str3.substring(1,5)); //Hell
        
        //六.其他
        //21.intern():返回字符串对象的规范表示。(将其存储在字符串常量池中)
        String str4 = str.intern();
        System.out.println(s == str4); //true
        System.out.println(str == str4); //false
        
        //22.concat(String str):将指定字符串连接的此字符串末尾
        System.out.println(s.concat("hijk")); //abcdefghijk
        
        //23.repeat(int count):将该字符串重复count次
        System.out.println(s.repeat(3)); //abcdefgabcdefgabcdefg
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值