java 常用API

1、Object类

Object类的概述

  • java.lang.Object类是Java语言中的根类,即所有类的父类。所有对象(包括数组)都实现了这个类的方法。

    如果一个类没有特别指定父类, 那么默认则继承自Object类。例如:

public class MyClass /*extends Object*/ {
  	// ...
}
public class Fu{
    
}
public class Zi extends Fu{
    // 间接继承Object类: Zi继承Fu,Fu继承Object类
}

Object类的构造方法

public Object()

Object类中常用方法

Object类当中包含的方法有11个。

  • public String toString():返回该对象的字符串表示。
  • public boolean equals(Object obj):指示其他某个对象是否与此对象“相等”

toString方法

toString方法的概述

  • public String toString():返回该对象的字符串表示,默认该字符串内容就是:类的全路径+@+十六进制数的地址值

由于toString方法返回的结果是内存地址,而在开发中,经常需要按照对象的属性得到相应的字符串表现形式,因此也需要重写它。

//重写toString方法
class Person{
    String name;
    int age;

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

    /*@Override
    public String toString() {
        // 自定义返回的字符串内容格式
        return name+","+age;
    }*/

    @Override
    public String toString() {
        // 使用快捷键生成默认格式(alt+insert)
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

在IntelliJ IDEA中,可以点击Code菜单中的Generate...,也可以使用快捷键alt+insert,点击toString()选项。选择需要包含的成员变量并确定。

小贴士: 在我们直接使用输出语句输出对象名的时候,其实通过该对象调用了其toString()方法。

equals方法

equals方法的概述

  • public boolean equals(Object obj):指示其他某个对象是否与此对象“相等”。

equals方法的使用

1、默认地址比较

Object类的equals()方法默认实心是==比较,也就是比较2个对象的地址值,对于我们来说没有用

由于java中所有类都是继承Object类,所以如果类中没有重写equals方法,默认就是地址值比较

2、对象内容比较

如果希望进行对象的内容比较,即所有或指定的部分成员变量相同就判定两个对象相同,则可以覆盖重写equals方法。例如:

class Person {
    String name;
    int age;

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

    /*@Override
    public boolean equals(Object obj) {
        // 自定义比较规则
        Person p = (Person) obj;
        return this.age == p.age && this.name.equals(p.name);
    }*/

    // 快捷键重写equals方法  alt+insert-->equals and hashCode
    @Override
    public boolean equals(Object o) {
        // 如果2个对象的地址值相同,就直接返回true,结束方法
        if (this == o) return true;
        // 如果传入的对象为null,就直接返回false,结束方法
        // 如果2个对象的类型不一致,就直接返回false,结束方法
        if (o == null || this.getClass() != o.getClass()) return false;
        // 来到这里,说明要比较的2个对象地址值不同,并且一定是Person类型
        Person person = (Person) o;// 向下转型
        //  比较所有属性是否相同
        return age == person.age &&
                Objects.equals(name, person.name);
    }
}

getClass方法

public final Class<?> getClass()
Returns the runtime class of this Object.

1.1 Objects类

JDK7添加了一个Objects工具类,它提供了一些方法来操作对象,它由一些静态的实用方法组成,这些方法是null-save(空指针安全的)或null-tolerant(容忍空指针的),用于计算对象的hashCode、返回对象的字符串表示形式、比较两个对象。

在比较两个对象的时候,Object的equals方法容易抛出空指针异常,而Objects类中的equals方法就优化了这个问题。方法如下:

  • public static boolean equals(Object a, Object b):判断两个对象是否相等。
public static int hash(Object... values) //为输入值序列生成散列代码
public static int hashCode(Object o)

public static String toString(Object o) //返回对象的字符串表示形式
public static String toString(Object o, String nullDefault) 
//Returns the result of calling toString on the first argument if the first argument is 
//not null and returns the second argument otherwise.

我们可以查看一下源码,学习一下:

public static boolean equals(Object a, Object b) {  
    return (a == b) || (a != null && a.equals(b));  
}
public class Test {
    public static void main(String[] args) {
        /*
            Objects类: 避免空指针异常(容忍空指针)
                public static boolean equals(Object a, Object b):判断两个对象是否相等。
                源码:
                     public static boolean equals(Object a, Object b) {
                        return (a == b) || (a != null && a.equals(b));
                    }
         */
        String name1 = "张三";
        String name2 = new String("张三");
        String name3 = null;
        System.out.println(name1);// 张三
        System.out.println(name2);// 张三

        // 比较name1和name2字符串内容是否相同
        //System.out.println(name1.equals(name2));// true
        //System.out.println(name3.equals(name1));// 空指针异常NullPointerException,因为null不能调用方法

        System.out.println(Objects.equals(name1, name2));// true
        System.out.println(Objects.equals(name3, name1));// false
    }
}

native方法

在Object类的源码中定义了 native 修饰的方法, native 修饰的方法称为本地方法。这种方法是没有方法体的,我们查看不了它的实现,所以大家不需要关心该方法如何实现的

  • 当我们需要访问C或C++的代码时,或者访问操作系统的底层类库时,可以使用本地方法实现。

    也就意味着Java可以和其它的编程语言进行交互。

  • 本地方法的作用: 就是当Java调用非Java代码的接口。方法的实现由非Java语言实现,比如C或C++。

Object类源码(部分):

package java.lang;
/**
 * Class {@code Object} is the root of the class hierarchy.
 * Every class has {@code Object} as a superclass. All objects,
 * including arrays, implement the methods of this class.
 *
 * @author  unascribed
 * @see     java.lang.Class
 * @since   JDK1.0
 */
public class Object {
	//本地方法
    private static native void registerNatives();
    //静态代码块
    static {
        registerNatives();
    }
    ......
    ......
}

2、Date类

Date类的概述

java.util.Date类 表示一个日期和时间,时间上的一个特定瞬间,精度为毫秒。

Date类中的构造方法

继续查阅Date类的描述,发现Date拥有多个构造函数,只是部分已经过时,我们重点看以下两个构造函数

  • public Date():从运行程序的此时此刻到时间原点经历的毫秒值,转换成Date对象,分配Date对象并初始化此对象,以表示分配它的时间(精确到毫秒)。
  • public Date(long date):将指定参数的毫秒值date,转换成Date对象,分配Date对象并初始化此对象,以表示自从标准基准时间(称为“历元(epoch)”,即1970年1月1日00:00:00 GMT)以来的指定毫秒数。

tips: 由于中国处于东八区(GMT+08:00)是比世界协调时间/格林尼治时间(GMT)快8小时的时区,当格林尼治标准时间为0:00时,东八区的标准时间为08:00。

简单来说:使用无参构造,可以自动设置当前系统时间的毫秒时刻;指定long类型的构造参数,可以自定义毫秒时刻。例如:

public class Test {
    public static void main(String[] args) {
        /*
            - Date类的概述: java.util.Date类 表示一个日期和时间,内部精确到毫秒。
            - Date类中的构造方法:
                    public Date() : 创建当前系统时间对应的日期对象
                    public Date(long date): 创建以标准基准时间为基准 指定偏移毫秒数 对应时间的日期对象
                        标准基准时间:
                            0时区: 1970年1月1日00:00:00 GMT
                            东8区: 1970年1月1日08:00:00 CST

			
         */
        // 创建当前统时间对应的日期对象
        Date date1 = new Date();
        System.out.println(date1);// Thu Sep 10 11:21:00 CST 2020

        // 创建以标准基准时间为基准 指定偏移1000毫秒
        Date date2 = new Date(1000);
        System.out.println(date2);// Thu Jan 01 08:00:01 CST 1970

        // 创建日期对象,表示1970年1月1日07:59:59
        Date date3 = new Date(-1000);
        System.out.println(date3);// Thu Jan 01 07:59:59 CST 1970

    }
}

tips:在使用println方法时,会自动调用Date类中的toString方法。Date类对Object类中的toString方法进行了覆盖重写,所以结果为指定格式的字符串。

GMT: Greenwich Mean Time 格林尼治时间

CST可以为如下4个不同的时区的缩写:
美国中部时间:Central Standard Time (USA) UT-6:00
澳大利亚中部时间:Central Standard Time (Australia) UT+9:30
中国标准时间:China Standard Time UT+8:00
古巴标准时间:Cuba Standard Time UT-4:00

Date类中的常用方法

Date类中的多数方法已经过时,常用的方法有:

  public long getTime() 获取当前日期对象距离标准基准时间的毫秒值。
  public void setTime(long time) 设置当前日期对象距离标准基准时间的毫秒值.也就意味着改变了当前日期对象
  
  public boolean after(Date when) 测试此日期是否在指定日期之后。
  public boolean before(Date when) 测试此日期是否在指定日期之前。
  
  public int compareTo(Date anotherDate) //如果参数Date等于此Date,则值为0 ; 
  						//如果此日期在Date参数之前,该值小于0 ; 如果此日期在Date参数之后则值大于0 

示例代码

public class Test2 {

    public static void main(String[] args) {
        /*
           - Date类中的常用方法
                - public long getTime() 获取当前日期对象距离标准基准时间的毫秒值。
                - public void setTime(long time) 设置当前日期对象距离标准基准时间的毫秒值.也就意味着改变了当前日期对象
                - public boolean after(Date when) 测试此日期是否在指定日期之后。
                - public boolean before(Date when) 测试此日期是否在指定日期之前。
         */
        // 创建当前统时间对应的日期对象
        Date date1 = new Date();
        System.out.println(date1);// Thu Sep 10 11:29:00 CST 2020

        // 创建以标准基准时间为基准 指定偏移1000毫秒
        Date date2 = new Date(1000);// 设置距离标准基准时间的毫秒值为1000
        System.out.println(date2);// Thu Jan 01 08:00:01 CST 1970

        // 获取当前日期对象距离标准基准时间的毫秒值。
        System.out.println(date1.getTime());// 1599708576604
        System.out.println(date2.getTime());// 1000

        // 修改date1距离标准基准时间的毫秒值为2000
        date1.setTime(2000);
        System.out.println(date1);// Thu Jan 01 08:00:02 CST 1970
        date2.setTime(2000);
        System.out.println(date2);// Thu Jan 01 08:00:02 CST 1970

        // 创建当前统时间对应的日期对象
        Date date3 = new Date();

        System.out.println("date3表示的日期是否在date1之前:"+date3.before(date1));//  false
        System.out.println("date3表示的日期是否在date1之后:"+date3.after(date1));//   true

    }
}

2.1 Duration

Date类的概述

一个Duration对象表示两个Instant间的一段时间,是在Java 8中加入的新功能。.
一个Duration实例是不可变的,当创建出对象后就不能改变它的值了。你只能通过Duration的计算方法,来创建出一个新的Durtaion对象。

一个Duration对象里有两个域:纳秒值(小于一秒的部分),秒钟值(一共有几秒)不包含毫秒

Date类中的构造方法

private Duration(long seconds, int nanos) 

//静态生成方法
public static Duration ofDays(long days)
public static Duration ofHours(long hours)
public static Duration ofMinutes(long minutes)
public static Duration ofSeconds(long seconds)
public static Duration ofMillis(long millis)
public static Duration ofNanos(long nanos)
public static Duration of(long amount, TemporalUnit unit)

Date类中的常用方法

public int getNano()
public long getSeconds()

//转换整个时间到其它单位如纳秒、分钟、小时、天
public long toNanos()
public long toMillis()
public long toMinutes()
public long toHours()
public long toDays()
private BigDecimal toSeconds()

//计算
public Duration plusNanos(long nanosToAdd)
plusMillis()
plusSeconds()
plusMinutes()
plusHours()
plusDays()
public Duration minusNanos(long nanosToSubtract)
minusMillis()
minusSeconds()
minusMinutes()
minusHours()
minusDays(

3、DateFormat类

DateFormat类的概述

java.text.DateFormat 是日期/时间格式化子类的抽象类,我们通过这个类可以帮我们完成日期和文本之间的转换,也就是可以在Date对象与String对象之间进行来回转换。

  • 格式化:按照指定的格式,把Date对象转换为String对象。
  • 解析:按照指定的格式,把String对象转换为Date对象。

由于DateFormat为抽象类,不能直接使用,所以需要常用的子类java.text.SimpleDateFormat。这个类需要一个模式(格式)来指定格式化或解析的标准。构造方法为:

  • public SimpleDateFormat(String pattern):用给定的模式和默认语言环境的日期格式符号构造SimpleDateFormat。参数pattern是一个字符串,代表日期时间的自定义格式。

格式规则

常用的格式规则为:

标识字母(区分大小写)含义
y
M
d
H
m
s
常见的日期格式:  yyyy年MM月dd日 HH时mm分ss秒
常见的日期格式:  yyyy-MM-dd HH:mm:ss
常见的日期格式:  yyyy-MM-dd
常见的日期格式:  HH:mm:ss

备注:更详细的格式规则,可以参考SimpleDateFormat类的API文档。

常用方法

DateFormat类的常用方法有:

  • public String format(Date date):将Date对象格式化为字符串。

  • public Date parse(String source):将字符串解析为Date对象。

public class Test {
    public static void main(String[] args) throws ParseException {
        // 1.需求: 把Date类型的对象转换为String类型
        // 创建当前日期对象
        Date date1 = new Date();

        // 创建日期格式化对象,并且指定日期格式
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化,日期格式随便指定

        // 使用日期格式化对象,把日期对象转换为String对象
        String dateStr = sdf1.format(date1);
        System.out.println(dateStr);// 2020-09-10 12:02:56

        System.out.println("===========================================");

        // 2.需求: 把String类型的对象转换为Date类型
        // 创建字符串对象
        String str = "2020年09月09日 12时00分00秒";

        // 创建日期格式化对象,并且指定日期格式
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");// 解析,日期格式要和字符串日期格式一样

        // 解析
        Date date = sdf2.parse(str);
        System.out.println(date);// Wed Sep 09 12:00:00 CST 2020
    }
}

4、Calendar类

Calendar类的概述

  • java.util.Calendar类表示一个“日历类”,可以进行日期运算。它是一个抽象类,不能创建对象,我们可以使用它的子类:java.util.GregorianCalendar类。
  • 有两种方式可以获取GregorianCalendar对象:
    • 直接创建GregorianCalendar对象;
    • 通过Calendar的静态方法getInstance()方法获取GregorianCalendar对象
      public static Calendar getInstance() 获取当前日期的日历对象
public class Test1 {
    public static void main(String[] args) {
        /*
                注意:
                    - 1.中国人:一个星期的第一天是星期一,外国人:一个星期的第一天是星期天
                    - 2.日历对象中的月份是: 0-11 对应实际月份的1-12

         */
        // 创建当前时间的日历对象
        Calendar cal = Calendar.getInstance();
        System.out.println(cal);
        /*
            java.util.GregorianCalendar[time=1599712166979,areFieldsSet=true,areAllFieldsSet=true,
            lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,
            dstSavings=0,useDaylight=false,transitions=19,lastRule=null],firstDayOfWeek=1,
            minimalDaysInFirstWeek=1,ERA=1,YEAR=2020,MONTH=8,WEEK_OF_YEAR=37,WEEK_OF_MONTH=2,
            DAY_OF_MONTH=10,DAY_OF_YEAR=254,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=0,
            HOUR_OF_DAY=12,MINUTE=29,SECOND=26,MILLISECOND=979,ZONE_OFFSET=28800000,DST_OFFSET=0]
         */
    }
}

Calendar类的常用方法

  • public static Calendar getInstance() 获取当前日期的日历对象

  • public int get(int field) 获取某个字段的值。

    • 参数field:表示获取哪个字段的值,可以使用Calender中定义的常量来表示
    • Calendar.YEAR : 年
      Calendar.MONTH :月
      Calendar.DAY_OF_MONTH:月中的日期
      Calendar.HOUR:小时
      Calendar.MINUTE:分钟
      Calendar.SECOND:秒
      Calendar.DAY_OF_WEEK:星期
  • public void set(int field,int value)设置某个字段的值

  • public void add(int field,int amount)为某个字段增加/减少指定的值

  • void setTime(Date date) 使用给定的 Date 设置此 Calendar 的时间。日历的值全部改了

  • boolean before(Object when)判断此 Calendar 表示的时间是否在指定 Object 表示的时间之前,返回判断结果。

    • 调用before方法的日历对象是否在参数时间对象之前,
      • 如果在之前就返回true 例如: 2017年11月11日 2019年12月18日 true
      • 如果不在之前就返回false 例如: 2019年12月18日 2017年11月11日 false
  • boolean after(Object when)判断此 Calendar 表示的时间是否在指定 Object 表示的时间之后,返回判断结果。

public class Test2 {
    public static void main(String[] args) throws ParseException {
        // 创建当前时间的日历对象
        Calendar cal = Calendar.getInstance();

        // 获取cal日历对象年字段的值
        int year = cal.get(Calendar.YEAR);
        System.out.println(year);// 2020

        // 获取cal日历对象月字段的值
        int month = cal.get(Calendar.MONTH);
        System.out.println(month);// 8

        // 设置cal日历对象中年字段的值为2030年
        cal.set(Calendar.YEAR,2030);
        System.out.println(cal.get(Calendar.YEAR));// 2030

        // 为cal日历对象的年字段的值+2
        cal.add(Calendar.YEAR,2);
        System.out.println(cal.get(Calendar.YEAR));// 2032

        // 为cal日历对象的年字段的值-1
        cal.add(Calendar.YEAR,-1);
        System.out.println(cal.get(Calendar.YEAR));// 2031
        System.out.println(cal.get(Calendar.MONTH));// 8

        System.out.println("==========================================");
        // 创建当前时间的日历对象
        Calendar cal1 = Calendar.getInstance();// 2020年09月10日

        // 需求: 获取1998年10月10日对应的日历对象
        String birthdayStr = "1998年10月10日";
        // 把字符串的日期转换为Date类型的日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        Date birthdayDate = sdf.parse(birthdayStr);

        // 调用cal的setTime方法,把日期对象传入
        cal1.setTime(birthdayDate);

        System.out.println("年:"+cal1.get(Calendar.YEAR));// 1998
        System.out.println("月:"+(cal1.get(Calendar.MONTH)+1));// 10
        System.out.println("日:"+cal1.get(Calendar.DAY_OF_MONTH));// 10

        System.out.println("==========================================");
        // 创建当前时间的日历对象
        Calendar cal2 = Calendar.getInstance();// 2020年09月10日
        System.out.println("cal1表示的时间是否在cal2表示的时间之前:"+cal1.before(cal2));// true
        System.out.println("cal1表示的时间是否在cal2表示的时间之后:"+cal1.after(cal2));// false

    }
}

5、Math类

Math类的概述

  • java.lang.Math(类): Math类包含执行基本数字运算的方法。如基本指数,对数,平方根和三角函数。
  • 它不能创建对象,它的构造方法被“私有”了。因为他内部都是“静态方法”,通过“类名”直接调用即可。

Math类的常用方法

//求绝对值
 public static int abs(int a) //获取参数a的绝对值:long int float double 
 
 //取整
 public static double ceil(double a) //向上取整  大于参数的最小整数  例如:3.14 向上取整4.0
如果参数值已经等于数学整数,则结果与参数相同。 
如果参数为NaN或无穷大或正零或负零,则结果与参数相同。 
如果参数值小于零但大于-1.0,则结果为负零。 

 public static double floor(double a) //向下取整 小于参数的最大整数  例如:3.14 向下取整3.0
 
 public static int round(float a) //返回参数最接近的int ,其中int四舍五入为正无穷大。 
 public static long round(double a) //返回参数中最接近的long ,其中long四舍五入为正无穷大。 四舍五入取整 例如:3.14 取整3  3.56 取整4
 
 //求幂
 public static double pow(double a, double b)  //获取a的b次幂
 
 //比较(求大小)
 public static int max(int a, int b)  // 返回两个 int 值中较大的一个。long int float double 
 public static int min(int a, int b)  // 返回两个 int 值中较小的一个。long int float double 
 

案例代码

public class Demo {
    public static void main(String[] args) {
        System.out.println("10的绝对值:"+Math.abs(10));// 10
        System.out.println("-10的绝对值:"+Math.abs(-10));// 10

        System.out.println("3.14向上取整:"+Math.ceil(3.14));// 4.0
        System.out.println("3.54向上取整:"+Math.ceil(3.54));// 4.0
        System.out.println("-3.54向上取整:"+Math.ceil(-3.54));// -3.0

        System.out.println("==================================");
        System.out.println("3.14向下取整:"+Math.floor(3.14));// 3.0
        System.out.println("3.54向下取整:"+Math.floor(3.54));// 3.0
        System.out.println("-3.54向下取整:"+Math.floor(-3.54));// -4.0

        System.out.println("==================================");
        System.out.println("2的3次幂:"+Math.pow(2,3));// 8.0

        System.out.println("==================================");
        System.out.println("3.14四舍五入取整:"+Math.round(3.14));// 3
        System.out.println("3.54四舍五入取整:"+Math.round(3.54));// 4
        System.out.println("-3.54四舍五入取整:"+Math.round(-3.54));// -4

        System.out.println("==================================");
        System.out.println("获取10和20的最大值:"+Math.max(10,20));// 20
        System.out.println("获取10和20的最小值:"+Math.min(10,20));// 10
    }
}

6、System类

System类的概述

java.lang.System类中提供了大量的静态方法,可以获取与系统相关的信息或系统级操作。

System类的常用方法

public static void exit(int status) 终止当前运行的Java虚拟机,非零表示异常终止

public static long currentTimeMillis() 返回当前时间距离标准基准时间的毫秒值(以毫秒为单位)

static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) 拷贝数组中的元素到另一个数组
      参数1src: 源数组
      参数2srcPos:源数组要拷贝的元素的起始索引(从哪个索引位置开始拷贝)
      参数3dest: 目标数组
      参数4destPos:目标数组接收拷贝元素的起始索引(从哪个索引位置开始接收)
      参数5length:需要拷贝多少个元素(拷贝多少个)

案例代码

public class Test {
    public static void main(String[] args) {
        System.out.println("开始");
        System.out.println("执行");
        //System.exit(0);// 程序正常退出
        //System.exit(-1);// 程序非正常退出

        // 获取当前时间距离标准基准时间的毫秒值
        Date date = new Date();
        System.out.println(date.getTime());
        System.out.println(System.currentTimeMillis());

        // 拷贝数组元素到另一个数组中
        int[] arr1 = {1,2,3,4,5,6,7,8};
        int[] arr2 = {10,20,30,40,50,60,70,80};
        // 需求:把arr1中的3,4,5,6,7元素拷贝到arr2数组中,使得arr2数组变成{10,3,4,5,6,7,70,80};
        System.arraycopy(arr1,2,arr2,1,5);

        // 遍历arr2数组
        for (int i = 0; i < arr2.length; i++) {
            System.out.print(arr2[i]+" ");
        }
        System.out.println();
        System.out.println("结束");
    }
}

7、BigInteger类

BigInteger类的概述

java.math.BigInteger 类,不可变的任意精度的整数。如果运算中,数据的范围超过了long类型后,可以使用BigInteger类实现,该类的计算整数是不限制长度的。

BigInteger类的构造方法

  • BigInteger(String value) 将 BigInteger 的十进制字符串表示形式转换为 BigInteger。超过long类型的范围,已经不能称为数字了,因此构造方法中采用字符串的形式来表示超大整数,将超大整数封装成BigInteger对象。
BigInteger(String val) 
//将BigInteger的十进制字符串表示形式转换为BigInteger。  
BigInteger(String val, int radix) 
//将指定基数中的BigInteger的String表示形式转换为BigInteger。  

BigInteger类成员方法

BigInteger类提供了对很大的整数进行加add、减subtract、乘multiply、除divide的方法,注意:都是与另一个BigInteger对象进行运算。

方法声明描述
add(BigInteger value)返回其值为 (this + val) 的 BigInteger,超大整数加法运算
subtract(BigInteger value)返回其值为 (this - val) 的 BigInteger,超大整数减法运算
multiply(BigInteger value)返回其值为 (this * val) 的 BigInteger,超大整数乘法运算
divide(BigInteger value)返回其值为 (this / val) 的 BigInteger,超大整数除法运算,除不尽取整数部分

【示例】

public class Test {
    public static void main(String[] args) {
        // 创建一个BigInteger类的对象,表示一个无限大的整数
        BigInteger b1 = new BigInteger("1000000000000000000000");
        BigInteger b2 = new BigInteger("1223435453543654354354");

        // b1 + b2
        BigInteger res1 = b1.add(b2);
        System.out.println("b1 + b2 = "+res1);// 2223435453543654354354

        // b1 - b2
        BigInteger res2 = b1.subtract(b2);
        System.out.println("b1 - b2 = " + res2);// -223435453543654354354

        // b1 * b2
        BigInteger res3 = b1.multiply(b2);
        System.out.println("b1 * b2 = "+res3);// 1223435453543654354354000000000000000000000

        // b1 / b2
        BigInteger res4 = b1.divide(b2);
        System.out.println("b1 / b2 = " + res4);// 0  10/3=3




        // int a = 1000000000000;// 编译报错,因为超出了int类型所能表示的数据范围
        // long l = 1000000000000000000000L;// 编译报错,因为超出了long类型所能表示的数据范围
    }
}

8、BigDecimal类

BigDecimal类的概述

java.math.BigDecimal,不可变的,任意精度的带符号的十进制数字。表示超大的小数,并且可以解决小数运算的精度问题

使用基本类型做浮点数运算精度问题;

看程序说结果:

public static void main(String[] args) {
    System.out.println(0.09 + 0.01);
    System.out.println(1.0 - 0.32);
    System.out.println(1.015 * 100);
    System.out.println(1.301 / 100);
}
  • 对于浮点运算,不要使用基本类型,而使用"BigDecimal类"类型

  • java.math.BigDecimal(类):提供了更加精准的数据计算方式。

BigDecimal类构造方法

构造方法名描述
BigDecimal(double val)将double类型的数据封装为BigDecimal对象
BigDecimal(String val)将 BigDecimal 的字符串表示形式转换为 BigDecimal

注意:推荐使用第二种方式字符串形式,第一种存在精度问题;

BigDecimal类常用方法

BigDecimal类中使用最多的还是提供的进行四则运算的方法,如下:

方法声明描述
public BigDecimal add(BigDecimal value)加法运算
public BigDecimal subtract(BigDecimal value)减法运算
public BigDecimal multiply(BigDecimal value)乘法运算
public BigDecimal divide(BigDecimal value)除法运算
public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)

注意:对于divide方法来说,如果除不尽的话,就会出现java.lang.ArithmeticException异常。此时可以使用divide方法的另一个重载方法;

BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode): divisor:除数对应的BigDecimal对象;scale:精确的位数;roundingMode取舍模式

RoundingMode枚举: RoundingMode.HALF_UP 四舍五入

public class Test {
    public static void main(String[] args) {
        // 加法运算:
        BigDecimal b1 = new BigDecimal("0.09");
        BigDecimal b2 = new BigDecimal("0.01");
        BigDecimal res1 = b1.add(b2);
        System.out.println("res1:"+res1);// 0.10

        // 减法运算:
        BigDecimal b3 = new BigDecimal("1.0");
        BigDecimal b4 = new BigDecimal("0.32");
        BigDecimal res2 = b3.subtract(b4);
        System.out.println("res2:"+res2);// 0.68

        // 乘法运算
        BigDecimal b5 = new BigDecimal("1.015");
        BigDecimal b6 = new BigDecimal("100");
        BigDecimal res3 = b5.multiply(b6);
        System.out.println("res3:"+res3);// 101.500

        // 除法运算
        BigDecimal b7 = new BigDecimal("1.301");
        BigDecimal b8 = new BigDecimal("100");
        BigDecimal res4 = b7.divide(b8);
        System.out.println("res4:"+res4);// 0.01301

        // 加法运算: 有问题的
        BigDecimal b9 = new BigDecimal(0.09);
        BigDecimal b10 = new BigDecimal(0.01);
        BigDecimal res5 = b9.add(b10);
        System.out.println("res5:"+res5);// res5:0.0999999999999999968774977432417472300585359334945678710937

        // 除法运算: 有问题的
        /*BigDecimal b11 = new BigDecimal("10");
        BigDecimal b12 = new BigDecimal("3");
        BigDecimal res6 = b11.divide(b12);// 报异常
        System.out.println("res6:"+res6);*/

        /*BigDecimal b13 = new BigDecimal("20");
        BigDecimal b14 = new BigDecimal("3");
        BigDecimal res7 = b13.divide(b14);// 报异常
        System.out.println("res7:"+res7);*/

        // 注意:对于divide方法来说,如果除不尽的话,
        // 就会出现java.lang.ArithmeticException异常。此时可以使用divide方法的另一个重载方法;
        BigDecimal b11 = new BigDecimal("10");
        BigDecimal b12 = new BigDecimal("3");
        BigDecimal res6 = b11.divide(b12,2, RoundingMode.HALF_UP);
        System.out.println("res6:"+res6);// 3.33

        BigDecimal b13 = new BigDecimal("20");
        BigDecimal b14 = new BigDecimal("3");
        BigDecimal res7 = b13.divide(b14,3,RoundingMode.HALF_UP);
        System.out.println("res7:"+res7);// 6.667


        // System.out.println(0.09+0.01);// 期望: 0.10     实际:0.09999999999999999
       // System.out.println(1.0 - 0.32);// 期望; 0.68    实际:0.6799999999999999
       // System.out.println(1.015 * 100);// 期望:101.500 实际:101.49999999999999
       // System.out.println(1.301 / 100);// 期望:0.01301 实际:0.013009999999999999
    }
}

9、Arrays类

Arrays类 见数组

10、包装类

包装类的概述

Java提供了两个类型系统,基本类型与引用类型,使用基本类型在于效率,然而很多情况,会创建对象使用,因为对象可以做更多的功能,如果想要我们的基本类型像对象一样操作,就可以使用基本类型对应的包装类,如下:

基本类型对应的包装类(位于java.lang包中)
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

Integer类

Integer类概述

Integer类在对象中包装基本类型int的值。 Integer类型的对象包含单个字段,其类型为int 。

此外,该类提供了几种将int转换为String和String转换为int ,以及处理int时有用的其他常量和方法。

Integer类构造方法及静态方法

构造方法

Integer(int value)   //已过时。
//构造一个新分配的 Integer对象,该对象表示指定的 int值。  
Integer(String s)	//已过时。
//构造一个新分配 Integer对象,表示 int由指示值 String参数。  

常用方法:

//生成Integer 对象
//int -> Integer
static Integer valueOf(int i)
//String -> Integer
static Integer valueOf(String s)
static Integer valueOf(String s, int radix) //一个是字符串,一个是基数。

valueOf() 方法用于返回给定参数的原生 Number 对象值,参数可以是原生数据类型, String等。

//类型转换
//Integer -> int long
public int intValue()  //以int 类型返回该Integer的值
public long longValue() //Returns the value of this Integer as a long
public double doubleValue()
public float floatValue()

//字符串转int
public static int parseInt(String s) //将字符串参数作为有符号的十进制整数进行解析
							 throws NumberFormatException
public static int parseInt(String s, int radix) //使用第二个参数指定的基数,将字符串参数解析为有符号的整数。
                throws NumberFormatException
//int转字符串
public static String toString(int i)
public static String toBinaryString(int i)


public static String toUnsignedString​(int i) //以无符号十进制值的形式返回参数的字符串表示形式。
public static String toUnsignedString​(int i, int radix)

11、Random

该类的实例用于生成伪随机数流。类使用48位种子,使用线性同余公式进行修改。(见Donald Knuth,《计算机编程的艺术》,第2卷,第3.2.1节)

如果用相同的种子创建了Random的两个实例,并且对每个实例进行了相同的方法调用序列,它们将生成并返回相同的数字序列。

Math.random() 使用更简单

random的实例是线程安全的。然而,跨线程并发使用相同的java.util.Random实例可能会遇到争用,从而导致性能低下。考虑在多线程设计中使用java.util.concurrent.ThreadLocalRandom。
random的实例在加密方面不是安全的。可以考虑使用java.security.SecureRandom来获得一个加密安全的伪随机数生成器,以供对安全敏感的应用程序使用。

Random的构造函数

public Random()
//创建一个新的随机数生成器。这个构造函数将随机数生成器的种子设置为一个很可能与此构造函数的任何其他
//调用不同的值。

public Random(long seed)
//使用一个种子创建一个新的随机数生成器。种子是伪随机数发生器内部状态的初值,然后用方法保持该初始值
//相当于Random rnd = new Random();
// rnd.setSeed(seed);


Random类常用方法

synchronized public void setSeed(long seed)
//setSeed的一般约定是,它改变这个随机数生成器对象的状态,使其处于完全相同的状态,
//就好像它刚刚用参数seed作为种子创建一样。

public int nextInt()
//从这个随机数生成器的序列返回下一个伪随机的、均匀分布的整型值。nextInt的一般约定是伪随机生成
//并返回一个整型值。所有2^32个可能的int值以(大约)相等的概率产生。

public int nextInt(int bound)
//返回一个伪随机的、均匀分布的int值,该值从这个随机数生成器的序列中抽取,
//介于0(包括)和指定值(不包括)之间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值