JAVA高级(三)

本文介绍了Java中日期时间API的使用,包括JDK8之前的Date、Calendar、SimpleDateFormat等,以及JDK8引入的新日期时间API,如LocalDate、LocalTime、LocalDateTime和Instant。新API解决了旧API的可变性、偏移性和格式化问题,提供了更易用的日期时间操作。此外,还涵盖了Java中的比较器、System类、Math类、BigInteger和BigDecimal的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JDK8之前日期时间API

java.lang.System类

System类提供的public static long currentTimeMillis()用来返回当前时 间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差。

        此方法适于计算时间差。

java.util.Date类

                |-----java.sql.Date类

        java.util.Date类

两个构造器的使用:

        Date():创建一个对应当前时间的Date对象

        创建指定毫秒数的Date对象

两个方法的使用:

        toString():显示当前的年、月、日、时、分、秒。

        getTime():获取当前Date对象对应的毫秒数(时间戳)

计算世界时间的主要标准有:

        UTC(Coordinated Universal Time)

        GMT(Greenwich Mean Time)

        CST(Central Standard Time)

java.sql.Date对应着数据库中的日期类型的变量

        如何将java.util.Date对象转换为java.sql.Date对象

package com.xxx.java;

import org.junit.Test;

import java.util.Date;

/**
 * @author Alkaid
 * @create 2022-08-15 19:32
 */
public class DateTimeTest {
    @Test
    public void test1() {
        long time = System.currentTimeMillis();
        System.out.println(time);

        Date date1 = new Date();

        System.out.println(date1.toString());
        System.out.println(date1.getTime());

        Date date2 = new Date(1660564009999L);
        System.out.println(date2.toString());

        //创建java.sql.Date对象
        java.sql.Date date3 = new java.sql.Date(35235325345L);
        System.out.println(date3);


//        情况一
        Date date4 = new java.sql.Date(35235325345L);
        java.sql.Date date5 = (java.sql.Date) date4;

//        情况二
        Date date6 = new Date();
        java.sql.Date date7 = new java.sql.Date(date6.getTime());
    }
}

java.text.SimpleDateFormat类

Date类的API不易于国际化,大部分被废弃了,java.text.SimpleDateFormat 类是一个不与语言环境有关的方式来格式化和解析日期的具体类。

它允许进行格式化:日期 ——> 文本

                     解析:文本 ——> 日期

package com.xxx.java;

import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Alkaid
 * @create 2022-08-16 11:34
 */
public class DateTimeTest {
    @Test
    public void testSimpleDateFormat() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat();

        Date date = new Date();
        System.out.println(date);

        String format = sdf.format(date);
        System.out.println(format);

        String str = "19-12-18 下午13:43";
        Date date1 = sdf.parse(str);
        System.out.println(date1);

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format1 = sdf1.format(date);
        System.out.println(format1);

        Date date2 = sdf1.parse(format1);
        System.out.println(date2);
    }

    @Test
    public void testExer() throws ParseException {
        String birth = "2020-09-08";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(birth);
        java.sql.Date birthDate = new java.sql.Date(date.getTime());
        System.out.println(birthDate);
    }
}

java.util.Calendar(日历)类

Calendar是一个抽象基类,主用用于完成日期字段之间相互操作的功能。

获取Calendar实例的方法

        使用Calendar.getInstance()方法

        调用它的子类GregorianCalendar的构造器。

一个Calendar的实例是系统时间的抽象表示,通过get(int field)方法来取得想 要的时间信息。比如YEAR、MONTH、DAY_OF_WEEK、HOUR_OF_DAY 、 MINUTE、SECOND

public void set(int field,int value)

public void add(int field,int amount)

public final Date getTime()

public final void setTime(Date date)

注意:

        获取月份时:一月是0,二月是1,以此类推,12月是11

        获取星期时:周日是1,周二是2 , 。。。。周六是7

package com.xxx.java;

import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author Alkaid
 * @create 2022-08-16 11:34
 */
public class DateTimeTest {
    @Test
    public void testSimpleDateFormat() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat();

        Date date = new Date();
        System.out.println(date);

        String format = sdf.format(date);
        System.out.println(format);

        String str = "19-12-18 下午13:43";
        Date date1 = sdf.parse(str);
        System.out.println(date1);

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format1 = sdf1.format(date);
        System.out.println(format1);

        Date date2 = sdf1.parse(format1);
        System.out.println(date2);
    }

    @Test
    public void testExer() throws ParseException {
        String birth = "2020-09-08";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(birth);
        java.sql.Date birthDate = new java.sql.Date(date.getTime());
        System.out.println(birthDate);
    }

    @Test
    public void testCalender(){
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.getClass());

        //常用方法
        //get()
        int days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR));

        //set()
        calendar.set(Calendar.DAY_OF_MONTH,22);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);

        //add()
        calendar.add(Calendar.DAY_OF_MONTH,-3);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);

        //getTime:日历类--->Date
        Date date = calendar.getTime();
        System.out.println(date);

        //setTime:Date--->日历类
        Date date1 = new Date();
        calendar.setTime(date1);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);

    }
}

JDK8中新日期时间API

新日期时间API出现的背景

如果我们可以跟别人说:“我们在1502643933071见面,别晚了!”那么就再简单不 过了。但是我们希望时间与昼夜和四季有关,于是事情就变复杂了。JDK 1.0中包含了 一个java.util.Date类,但是它的大多数方法已经在JDK 1.1引入Calendar类之后被弃用 了。而Calendar并不比Date好多少。它们面临的问题是:

        可变性:像日期和时间这样的类应该是不可变的。

        偏移性:Date中的年份是从1900开始的,而月份都从0开始。

        格式化:格式化只对Date有用,Calendar则不行。

        此外,它们也不是线程安全的;不能处理闰秒等。

总结:对日期和时间的操作一直是Java程序员最痛苦的地方之一。

新时间日期API

第三次引入的API是成功的,并且Java 8中引入的java.time API 已经纠正了 过去的缺陷,将来很长一段时间内它都会为我们服务。

Java 8 吸收了 Joda-Time 的精华,以一个新的开始为 Java 创建优秀的 API。 新的 java.time 中包含了所有关于本地日期(LocalDate)、本地时间 (LocalTime)、本地日期时间(LocalDateTime)、时区(ZonedDateTime) 和持续时间(Duration)的类。历史悠久的 Date 类新增了 toInstant() 方法, 用于把 Date 转换成新的表示形式。这些新增的本地化时间日期 API 大大简 化了日期时间和本地化的管理。

java.time – 包含值对象的基础包

java.time.chrono – 提供对不同的日历系统的访问

java.time.format – 格式化和解析时间和日期

java.time.temporal – 包括底层框架和扩展特性

java.time.zone – 包含时区支持的类

说明:大多数开发者只会用到基础包和format包,也可能会用到temporal包。因此,尽 管有68个新的公开类型,大多数开发者,大概将只会用到其中的三分之一。

LocalDate、LocalTime、LocalDateTime

LocalDate、LocalTime、LocalDateTime 类是其中较重要的几个类,它们的实例 是不可变的对象,分别表示使用 ISO-8601日历系统的日期、时间、日期和时间。 它们提供了简单的本地日期或时间,并不包含当前的时间信息,也不包含与时区 相关的信息。

        LocalDate代表IOS格式(yyyy-MM-dd)的日期,可以存储 生日、纪念日等日期。

        LocalTime表示一个时间,而不是日期。

        LocalDateTime是用来表示日期和时间的,这是一个最常用的类之一。

 说明:LocalDateTime相较于LocalDate、LocalTime,使用频率更高

瞬时:Instant

Instant:时间线上的一个瞬时点。 这可能被用来记录应用程序中的事件时间戳。

在处理时间和日期的时候,我们通常会想到年,月,日,时,分,秒。然而,这只是 时间的一个模型,是面向人类的。第二种通用模型是面向机器的,或者说是连 续的。在此模型中,时间线中的一个点表示为一个很大的数,这有利于计算机 处理。在UNIX中,这个数从1970年开始,以秒为的单位;同样的,在Java中, 也是从1970年开始,但以毫秒为单位。

 java.time.format.DateTimeFormatter 类:

格式化或解析日期、时间

类似于SimpleDateFormat

该类提供了三种格式化方法:

        预定义的标准格式。如:

                ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME

        本地化相关的格式。如:ofLocalizedDateTime(FormatStyle.LONG)

        自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)

package com.xxx.java;

import org.junit.Test;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;
import java.util.Date;

/**
 * @author Alkaid
 * @create 2022-08-16 17:06
 */
public class JDK8DateTimeTest {
    @Test
    public void testDate(){
        Date date = new Date(2020-1900, 9-1, 8);
        System.out.println(date);
    }

    @Test
    public void test1(){
        //now:获取当前的日期、时间、日期+时间
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();

        System.out.println(localDate);
        System.out.println(localTime);
        System.out.println(localDateTime);

        //of    设置指定的年、月、日、时、分、秒、没有偏移量
        LocalDateTime localDateTime1 = LocalDateTime.of(2022,10,25,19,30,00);
        System.out.println(localDateTime1);

        //getXxx:获取相关的属性
        System.out.println(localDateTime1.getDayOfMonth());
        System.out.println(localDateTime1.getDayOfYear());
        System.out.println(localDateTime1.getMonth());
        System.out.println(localDateTime1.getMonthValue());
        System.out.println(localDateTime1.getMinute());

        //体现不可变性
        //with:设置相关的属性
        LocalDateTime localDateTime2 = localDateTime.withDayOfMonth(22);
        System.out.println(localDateTime);
        System.out.println(localDateTime2);

        LocalDateTime localDateTime3 = localDateTime.withHour(22);
        System.out.println(localDateTime);
        System.out.println(localDateTime3);

        //不可变性
        LocalDateTime localDateTime4 = localDateTime.plusMonths(3);
        System.out.println(localDateTime);
        System.out.println(localDateTime4);

        LocalDateTime localDateTime5 = localDateTime.minusDays(6);
        System.out.println(localDateTime);
        System.out.println(localDateTime5);
    }

    @Test
    public void test2(){
        //now获取本初子午线对应的标准时间
        Instant instant = Instant.now();
        System.out.println(instant);//本初子午线时间2022-08-16T12:52:51.265Z

        //中国时区/添加时间偏移量
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);

        //toEpochMilli获取对应的毫秒数1970-01-01 00:00:00到当前时间的毫秒数 --> Date类的getTime()方法
        long milli = instant.toEpochMilli();
        System.out.println(milli);

        //ofEpochMilli():通过给定的毫秒数,获取Instant实例  --> Date(long millis)
        Instant instant1 = Instant.ofEpochMilli(1660654729726L);
        System.out.println(instant1);
    }

    @Test
    public void test3(){
        //方式一:预定义
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

        //格式化:日期 --> 字符串
        LocalDateTime date1 = LocalDateTime.now();
        String str1 = formatter.format(date1);
        System.out.println(date1);
        System.out.println(str1);

        //解析:字符串 --> 日期
        TemporalAccessor parse = formatter.parse(str1);
        System.out.println(parse);

        //方式二:本地相关的格式:
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);

        //格式化
        String str2 = formatter1.format(date1);
        System.out.println(str2);

        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        //格式化
        String str3 = formatter2.format(LocalDate.now());
        System.out.println(str3);

        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");

        //格式化
        String str4 = formatter3.format(LocalDateTime.now());
        System.out.println(str4);

        //解析
        System.out.println(formatter3.parse(str4));

    }
}

其他API

ZoneId:该类中包含了所有的时区信息,一个时区的ID,如 Europe/Paris

ZonedDateTime:一个在ISO-8601日历系统时区的日期时间,如 2007-12- 03T10:15:30+01:00 Europe/Paris。

        其中每个时区都对应着ID,地区ID都为“{区域}/{城市}”的格式,例如: Asia/Shanghai等

        //ZoneId:类中包含了所有的时区信息
        // ZoneId的getAvailableZoneIds():获取所有的ZoneId
        Set<String> zoneIds = ZoneId.getAvailableZoneIds();
        for (String s : zoneIds) {
            System.out.println(s);
        }
        // ZoneId的of():获取指定时区的时间
        LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of("Asia/Tokyo"));
        System.out.println(localDateTime);
        //ZonedDateTime:带时区的日期时间
        // ZonedDateTime的now():获取本时区的ZonedDateTime对象
        ZonedDateTime zonedDateTime = ZonedDateTime.now();
        System.out.println(zonedDateTime);
        // ZonedDateTime的now(ZoneId id):获取指定时区的ZonedDateTime对象
        ZonedDateTime zonedDateTime1 = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
        System.out.println(zonedDateTime1);

Clock:使用时区提供对当前即时、日期和时间的访问的时钟。

        持续时间:Duration,用于计算两个“时间”间隔

        日期间隔:Period,用于计算两个“日期”间隔

  //Duration:用于计算两个“时间”间隔,以秒和纳秒为基准
        LocalTime localTime = LocalTime.now();
        LocalTime localTime1 = LocalTime.of(15, 23, 32);
        //between():静态方法,返回Duration对象,表示两个时间的间隔
        Duration duration = Duration.between(localTime1, localTime);
        System.out.println(duration);
        System.out.println(duration.getSeconds());
        System.out.println(duration.getNano());
        LocalDateTime localDateTime = LocalDateTime.of(2016, 6, 12, 15, 23, 32);
        LocalDateTime localDateTime1 = LocalDateTime.of(2017, 6, 12, 15, 23, 32);
        Duration duration1 = Duration.between(localDateTime1, localDateTime);
        System.out.println(duration1.toDays());

        //Period:用于计算两个“日期”间隔,以年、月、日衡量
        LocalDate localDate = LocalDate.now();
        LocalDate localDate1 = LocalDate.of(2028, 3, 18);
        Period period = Period.between(localDate, localDate1);
        System.out.println(period);
        System.out.println(period.getYears());
        System.out.println(period.getMonths());
        System.out.println(period.getDays());
        Period period1 = period.withYears(2);
        System.out.println(period1);

TemporalAdjuster : 时间校正器。有时我们可能需要获取例如:将日期调整 到“下一个工作日”等操作。

TemporalAdjusters : 该类通过静态方法 (firstDayOfXxx()/lastDayOfXxx()/nextXxx())提供了大量的常用 TemporalAdjuster 的实现。

        // TemporalAdjuster:时间校正器
        // 获取当前日期的下一个周日是哪天?
        TemporalAdjuster temporalAdjuster = TemporalAdjusters.next(DayOfWeek.SUNDAY);
        LocalDateTime localDateTime = LocalDateTime.now().with(temporalAdjuster);
        System.out.println(localDateTime);
        // 获取下一个工作日是哪天?
        LocalDate localDate = LocalDate.now().with(new TemporalAdjuster() {
            @Override
            public Temporal adjustInto(Temporal temporal) {
                LocalDate date = (LocalDate) temporal;
                if (date.getDayOfWeek().equals(DayOfWeek.FRIDAY)) {
                    return date.plusDays(3);
                } else if (date.getDayOfWeek().equals(DayOfWeek.SATURDAY)) {
                    return date.plusDays(2);
                } else {
                    return date.plusDays(1);
                }
            }
        });
        System.out.println("下一个工作日是:" + localDate);

 IDEA导入module

齿轮——Project  Structure

 加号——Import Module

 之后按需求选择

 Java比较器

在Java中经常会涉及到对象数组的排序问题,那么就涉及到对象之间 的比较问题。

 Java实现对象排序的方式有两种:

        自然排序:java.lang.Comparable

        定制排序:java.util.Comparator

  自然排序

Comparable接口的使用举例:(自然排序)

        Stirng、包装类等实现了Comparable接口,重写了compareTo(obj)方法,给出了比较两个对象大小的方式

        像String、包装类重写compareTo(obj)方法以后,进行了从小到大的排列。

重写compareTo(obj)的规则:

        如果当前对象this大于形参对象obj,则返回正整数,

        如果当前对象this小于形参对象obj,则返回 负整数,

        如果当前对象this等于形参对象obj,则返回零。

对于自定义类来说,如果需要排序,我们可以让自定义类实现Comparable接口,重写compareTo(obj)方法。在compareTo(obj)方法中指明如何排序

定制排序

Comparator接口的使用:定制排序

1.背景:

当元素的类型没有实现java.lang.Comparable接口而又不方便修改代码,

或者实现了java.lang.Comparable接口的排序规则不适合当前的操作,

那么可以考虑使用 Comparator 的对象来排序

2.重写compare(Object o1,Object o2)方法,比较o1和o2的大小:

如果方法返回正整数,则表示o1大于o2;

如果返回0,表示相等;

返回负整数,表示 o1小于o2。

Comparable接口与Comparator的使用对比:

Comparable接口的方式一旦指定,保证Comparable接口实现类的对象在任何位置都可以比较大小

Comparator接口属于临时性的比较。

package com.xxx.java;

/**
 * @author Alkaid
 * @create 2022-08-16 21:52
 */
public class Goods implements Comparable{

    private String name;
    private double price;

    public Goods() {
    }

    public Goods(String name, double price) {
        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 "Goods{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    //按照价格从低到高排序,产品名称从低到高。
    @Override
    public int compareTo(Object o) {
        if(o instanceof  Goods){

            Goods goods = (Goods)o;

            //方式一
            if(this.price > goods.price){
                return 1;
            }else if(this.price < goods.price){
                return -1;
            }else {
                return this.name.compareTo(this.name);
            }
            //方式二
            //return Double.compare(this.price,goods.price);
        }
        throw new RuntimeException("传入的数据类型不一致!");
    }


}
package com.xxx.java;

import org.junit.Test;

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

/**
 * @author Alkaid
 * @create 2022-08-16 21:39
 */
public class CompareTest {
    @Test
    public void test1() {
        String[] arr = new String[]{"AA", "CC", "KK", "MM", "GG", "JJ", "DD"};

        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
    }

    @Test
    public void test2() {
        Goods[] arr = new Goods[5];
        arr[0] = new Goods("lenovoMouse", 34);
        arr[1] = new Goods("dellMouse", 43);
        arr[2] = new Goods("miMouse", 12);
        arr[3] = new Goods("huaweiMouse", 65);
        arr[4] = new Goods("microsoftMouse", 43);

        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
    }

    @Test
    public void test3() {
        String[] arr = new String[]{"AA", "CC", "KK", "MM", "GG", "JJ", "DD"};
        Arrays.sort(arr, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof String && o2 instanceof String) {
                    String s1 = (String) o1;
                    String s2 = (String) o2;
                    return -s1.compareTo(s2);
                }
                throw new RuntimeException("输入的数据类型有误");
            }


        });
        System.out.println(Arrays.toString(arr));
    }

    @Test
    public void test4(){
        Goods[] arr = new Goods[6];
        arr[0] = new Goods("lenovoMouse", 34);
        arr[1] = new Goods("dellMouse", 43);
        arr[2] = new Goods("miMouse", 12);
        arr[3] = new Goods("huaweiMouse", 65);
        arr[4] = new Goods("microsoftMouse", 43);
        arr[5] = new Goods("microsoftMouse", 224);

        Arrays.sort(arr, new Comparator() {
            //按照产品名称从低到高,价格从高到低排序
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof  Goods && o2 instanceof Goods) {

                    Goods g1 = (Goods) o1;
                    Goods g2 = (Goods) o2;

                    if(g1.getName().equals(g2.getName())){
                        if(g1.getPrice() > g2.getPrice()){
                            return -1;
                        }else if(g1.getPrice() < g2.getPrice()){
                            return 1;
                        }else {
                            return 0;
                        }
                    }else{
                        return g1.getName().compareTo(g2.getName());
                    }

                }
                throw new RuntimeException("传入的数据类型不一致!");
            }
        });
        System.out.println(Arrays.toString(arr));
    }
}

System类

System类代表系统,系统级的很多属性和控制方法都放置在该类的内部。 该类位于java.lang包。

由于该类的构造器是private的,所以无法创建该类的对象,也就是无法实例化该类。其内部的成员变量和成员方法都是static的,所以也可以很方便的进行调用。

成员变量

        System类内部包含in、out和err三个成员变量,分别代表标准输入流 (键盘输入),标准输出流(显示器)和标准错误输出流(显示器)。

成员方法

        native long currentTimeMillis():

该方法的作用是返回当前的计算机时间,时间的表达格式为当前计算机时 间和GMT时间(格林威治时间)1970年1月1号0时0分0秒所差的毫秒数。

        void exit(int status):

该方法的作用是退出程序。其中status的值为0代表正常退出,非零代表 异常退出。使用该方法可以在图形界面编程中实现程序的退出功能等。

        void gc():

该方法的作用是请求系统进行垃圾回收。至于系统是否立刻回收,则取决于系统中垃圾回收算法的实现以及系统执行时的情况。

        String getProperty(String key):

该方法的作用是获得系统中属性名为key的属性对应的值。系统中常见 的属性名以及属性的作用如下表所示:

 Math类

java.lang.Math提供了一系列静态方法用于科学计算。其方法的参数和返回 值类型一般为double型。

abs 绝对值

acos,asin,atan,cos,sin,tan 三角函数

sqrt 平方根

pow(double a,doble b) a的b次幂

log 自然对数

exp e为底指数

max(double a,double b)

min(double a,double b)

random() 返回0.0到1.0的随机数

long round(double a) double型数据a转换为long型(四舍五入)

toDegrees(double angrad) 弧度—>角度

toRadians(double angdeg) 角度—>弧度

BigInteger与BigDecimal

BigInteger类

Integer类作为int的包装类,能存储的最大整型值为2 31-1,Long类也是有限的, 最大为2 63-1。如果要表示再大的整数,不管是基本数据类型还是他们的包装类 都无能为力,更不用说进行运算了。

java.math包的BigInteger可以表示不可变的任意精度的整数。BigInteger 提供 所有 Java 的基本整数操作符的对应物,并提供 java.lang.Math 的所有相关方法。 另外,BigInteger 还提供以下运算:模算术、GCD 计算、质数测试、素数生成、 位操作以及一些其他操作。

构造器

        BigInteger(String val):根据字符串构建BigInteger对象

常用方法

public BigInteger abs():返回此 BigInteger 的绝对值的 BigInteger。

BigInteger add(BigInteger val) :返回其值为 (this + val) 的 BigInteger

BigInteger subtract(BigInteger val) :返回其值为 (this - val) 的 BigInteger

BigInteger multiply(BigInteger val) :返回其值为 (this * val) 的 BigInteger

BigInteger divide(BigInteger val) :返回其值为 (this / val) 的 BigInteger。整数 相除只保留整数部分。 

BigInteger remainder(BigInteger val) :返回其值为 (this % val) 的 BigInteger。

BigInteger[] divideAndRemainder(BigInteger val):返回包含 (this / val) 后跟 (this % val) 的两个 BigInteger 的数组。

BigInteger pow(int exponent) :返回其值为 (thisexponent) 的 BigInteger。

BigDecimal类

一般的Float类和Double类可以用来做科学计算或工程计算,但在商业计算中, 要求数字精度比较高,故用到java.math.BigDecimal类。

BigDecimal类支持不可变的、任意精度的有符号十进制定点数。

构造器

        public BigDecimal(double val)

        public BigDecimal(String val)

常用方法

        public BigDecimal add(BigDecimal augend)

        public BigDecimal subtract(BigDecimal subtrahend)

        public BigDecimal multiply(BigDecimal multiplicand)

        public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)

package com.xxx.java;

import org.junit.Test;

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

/**
 * @author Alkaid
 * @create 2022-08-16 22:55
 */
public class OtherClass {
    @Test
    public void test1(){
        String javaVersion = System.getProperty("java.version");
        System.out.println("java的version:" + javaVersion);

        String javaHome = System.getProperty("java.home");
        System.out.println("java的home:" + javaHome);

        String osName = System.getProperty("os.name");
        System.out.println("os的name:" + osName);

        String osVersion = System.getProperty("os.version");
        System.out.println("os的version:" + osVersion);

        String userName = System.getProperty("user.name");
        System.out.println("user的name:" + userName);

        String userHome = System.getProperty("user.home");
        System.out.println("user的home:" + userHome);

        String userDir = System.getProperty("user.dir");
        System.out.println("user的dir:" + userDir);
    }
    @Test
    public void testBigInteger() {
        BigInteger bi = new BigInteger("124332414156156165165165156123");
        BigDecimal bd = new BigDecimal("12435.351");
        BigDecimal bd2 = new BigDecimal("11");
        System.out.println(bi);
        // System.out.println(bd.divide(bd2));  报错
        System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP));
        System.out.println(bd.divide(bd2, 15, BigDecimal.ROUND_HALF_UP));
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值