01-12、JavaSE知识点总结_Java常用类

字符串相关的类

String类及常用方法

String的特性
1.Java程序中的所有 字符串字面值(如"abc")都是String类的对象
2.String类是一个final类
3.字符串是常量,用双引号引起来表示,它们的值在创建之后不能更改
4.String对象的字符内容是存储在一个字符数组value[]中的
5.Java运行期字符串常量池中有一个表,为池中每个唯一的字符串对象维护一个引用,意味着一直存在引用字符串常量池中的对象,所以,字符串常量池中的字符串不会被垃圾收集器回收
public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];
}

在Java中String类为什么要设计成final
简而言之:为了安全,char[]使用final防止引用地址的变化,char[]使用private防止子类继承,String使用final防止重写父类方法修改char[]数组的内容,综合下来String类是安全的

  • String对象的创建
    • String str = “hello”;
    • //this.value = “”.value;
      String s1 = new String();
    • //this.value = original.value;
      String s2 = new String(String original);
    • //this.value = Arrays.copyOf(value, value.length);
      String s3 = new String(char[] value);
    • String s4 = new String(char[] value,int startIndex,int count);

在这里插入图片描述

String str1 = “abc”;与String str2 = new String(“abc”);的区别
字符串常量存储在字符串常量池中,目的是共享
字符串非常量对象存储在堆中
在这里插入图片描述
字符串的特性
1.常量与常量的拼接结果在常量池(因为在编译阶段做了优化),且常量池中不会存在相同内容的常量
2.只要其中有一个是变量(因为编译阶段对变量无法优化),结果就在堆中
3.如果拼接的结果调用intern()方法,返回值就在常量池中
在这里插入图片描述
  • String使用陷阱
    • String s1 = “a”;
      在字符串常量池中创建了一个字面量为"a"的字符串
    • s1 = s1 + “b”;
      在堆空间中产生了一个字符串s1+“b”(也就是"ab")
    • String s2 = “ab”;
      直接在字符串常量池中创建一个字面量为"ab"的字符串
    • String s3 = “a” + “b”;
      s3指向字符串常量池中已经创建的"ab"的字符串
    • String s4 = s1.intern();
      堆空间的s1对象在调用intern()之后,会将常量池中的"ab"字符串赋值给s4

汇编指令解析String对象

构造方法
public String()
public String(byte bytes[])
public String(byte bytes[], Charset charset)
public String(byte bytes[], int offset, int length)
public String(byte bytes[], int offset, int length, Charset charset)
public String(byte bytes[], int offset, int length, String charsetName)
public String(byte bytes[], String charsetName)
public String(char value[])
public String(char value[], int offset, int count)
public String(int[] codePoints, int offset, int count)
public String(String original)
public String(StringBuffer buffer)
public String(StringBuilder builder)
常用方法解释
int length()返回字符串的长度:return value.length
char charAt(int index)返回某索引处的字符return value[index]
boolean isEmpty()判断是否是空字符串:return value.length == 0
String toLowerCase()使用默认语言环境,将String中的所有字符转换为小写
String toUpperCase()使用默认语言环境,将String中的所有字符转换为大写
String trim()返回字符串的副本,忽略字符串开始的空白和尾部空白
boolean equals(Object obj)比较字符串的内容是否相同
boolean equalsIgnoreCase(String anotherString)与equals方法类似,忽略大小写
String concat(String str)将指定字符串连接到此字符串的结尾,等价于“+”
int compareTo(String anotherString)比较两个字符串的大小
String substring(int beginIndex)返回一个新的字符串,它是此字符串的从beginIndex开始截取到最后的一个子字符串
String substring(int beginIndex, int endIndex)返回一个新字符串,它是此字符串从beginIndex开始截取到endIndex(不包含)的一个子字符串
boolean endsWith(String suffix)测试此字符串是否以指定的后缀结束
boolean startsWith(String prefix)测试此字符串是否以指定的前缀开始
boolean startsWith(String prefix, int toffset)测试此字符串从指定索引开始的子字符串是否以指定前缀开始
boolean contains(CharSequence s)当且仅当此字符串包含指定的char值序列时,返回 true
int indexOf(String str)返回指定子字符串在此字符串中第一次出现处的索引,未找到返回-1
int indexOf(String str, int fromIndex)返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始,未找到返回-1
int lastIndexOf(String str)返回指定子字符串在此字符串中最右边出现处的索引,未找到返回-1
int lastIndexOf(String str, int fromIndex)返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索,未找到返回-1
String replace(char oldChar, char newChar)返回一个新的字符串,它是通过用newChar替换此字符串中出现的所有oldChar得到的
String replace(CharSequence target, CharSequence replacement)使用指定的字面值替换序列替换此字符串所有匹配字面值目标序列的子字符串
String replaceAll(String regex, String replacement)使用给定的replacement替换此字符串所有匹配给定的正则表达式的子字符串
String replaceFirst(String regex, String replacement)使用给定的replacement替换此字符串匹配给定的正则表达式的第一个子字符串
boolean matches(String regex)告知此字符串是否匹配给定的正则表达式
String[] split(String regex)根据给定正则表达式的匹配拆分此字符串
String[] split(String regex, int limit)根据匹配给定的正则表达式来拆分此字符串,最多不超过limit个,如果超过了,剩下的全部都放到最后一个元素中

Java正则表达式|菜鸟教程

  • String与基本数据类型转换
    • 字符串→基本数据类型、包装类
      • Integer包装类的public static int parseInt(String s),可以将由“数字”字符组成的字符串转换为整型
      • 类似地,使用java.lang包中的Byte、Short、Long、Float、Double类调相应的类方法可以将由“数字”字符组成的字符串,转化为相应的基本数据类型
    • 基本数据类型、包装类→字符串
      • 调用String类的public String valueOf(int n)可将int型转换为字符串
      • 相应的valueOf(byte b)、valueOf(long l)、valueOf(float f)、valueOf(doubled)、valueOf(boolean b)可由参数的相应类型到字符串的转换
    • 字符数组→字符串
      • String类的构造器:String(char[])和String(char[],int offset,int length)分别用字符数组中的全部字符和部分字符创建字符串对象
    • 字符串→字符数组
      • public char[] toCharArray():将字符串中的全部字符存放在一个字符数组中
      • public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin):提供了将指定索引范围内的字符串存放到数组中的方法
    • 字节数组→字符串
      • String(byte[]):通过使用平台的默认字符集解码指定的byte数组,构造一个新的String
      • String(byte[],int offset,int length):用指定的字节数组的一部分,即从数组起始位置offset开始取length个字节构造一个字符串对象
    • 字符串→字节数组
      • public byte[] getBytes():使用平台的默认字符集将此String编码为byte序列,并将结果存储到一个新的byte数组中
      • public byte[] getBytes(“UTF-8”):使用UTF-8字符集将此String编码为byte序列,并将结果存储到一个新的byte数组中
      • public byte[] getBytes(String charsetName):使用指定的字符集将此String编码到byte序列,并将结果存储到新的byte数组

StringBuffer、StringBuilder

StringBuffer类
1.java.lang.StringBuffer代表可变的字符序列,JDK1.0中声明,可以对字符串内容进行增删,此时不会产生新的对象
2.JDK8中StringBuffer中大多数方法都是调用父类AbstractStringBuilder中的属性和方法完成的
3.很多方法与String相同
4.作为参数传递时,方法内部可以改变值
abstract class AbstractStringBuilder implements Appendable, CharSequence {
    /**
     * The value is used for character storage.
     */
    char[] value;
}

 public final class StringBuffer
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
{

    /**
     * A cache of the last value returned by toString. Cleared whenever the StringBuffer is modified.
     */
    private transient char[] toStringCache;

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    static final long serialVersionUID = 3388685877147921107L;

    /**
     * Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
     */
    public StringBuffer() {
        super(16);
    }
}

      StringBuffer类不同于String,其对象必须使用构造器生成

方法解释
StringBuffer()初始容量为16的字符串缓冲区
StringBuffer(int size)构造指定容量的字符串缓冲区
StringBuffer(String str)将内容初始化为指定字符串内容

      StringBuffer类的常用方法

方法解释
StringBuffer append(xxx)提供了很多的append()方法,用于进行字符串拼接,char[]数组长度不够,可扩容
StringBuffer delete(int start,int end)删除指定位置的内容
StringBuffer deleteCharAt(int index)删除指定索引位置的字符
StringBuffer replace(int start, int end, String str)把[start,end)位置替换为str
StringBuffer insert(int offset, xxx)在指定位置插入xxx,原来value数组长度不够,可扩容
StringBuffer reverse()把当前字符序列逆转
public int indexOf(String str)返回指定子字符串第一次出现处的索引,未找到返回-1
public int lastIndexOf(String str)从后往前查找指定子字符串第一次出现处的索引,未找到返回-1
public String substring(int start,int end)截取生成新的字符串
CharSequence subSequence(int start, int end)截取返回字符序列,即字符串
public int length()字符串长度
public char charAt(int n)返回某索引处的字符
public void setCharAt(int n ,char ch)指定索引位置修改为指定的char
public int capacity()char[]数组长度,如果数组大小不够存储新添加的字符串时,char数组需要扩容
void ensureCapacity(int minimumCapacity)char[]数组扩容
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)将字符串srcBegin到srcEnd索引(包头不包尾)之间的字符赋值到dst字符数组中(从dstBegin索引处开始)
public void setLength(int newLength)将字符串长度调整到指定长度,newLength小于字符串长度截取,否则填充’\0’
void readObject(java.io.ObjectInputStream s)反序列化
int offsetByCodePoints(int index, int codePointOffset)返回此序列中的索引,该索引是从给定index偏移 codepointoffset个代码点后得到的,index和codepointoffset给出的文本范围内的不成对代理项是按一个代码点算作一个项进行计数的
String toString()return new String(Arrays.copyOfRange(value, 0, count);, true);
void trimToSize()如果char数组容量大于字符串长度,将char数组容量减少到等于字符串长度
void writeObject(java.io.ObjectOutputStream s)序列化
StringBuilder类
StringBuilder和StringBuffer非常类似,均代表可变的字符序列,而且提供相关功能的方法也一样

String,StringBuffer,StringBuilder分析

      对比String、StringBuffer、StringBuilder

不同点
String(JDK1.0)不可变字符序列
StringBuffer(JDK1.0)可变字符序列、效率低、线程安全
StringBuilder(JDK 5.0)可变字符序列、效率高、线程不安全
  • 作为参数传递的话,方法内部String不会改变其值,StringBuffer和StringBuilder会改变其值,可参考面试题部分第一题

      如何优化StringBuffer的性能

  • 创建StringBuffer对象时尽量给定一个合适的初始化容量,减少扩容的次数

JDK8之前的日期时间API

java.lang.System静态方法

  • System类提供的public static long currentTimeMillis()用来返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差
  • 计算世界时间的主要标准有
       UTC(Coordinated Universal Time)
       GMT(Greenwich Mean Time)
       CST(Central Standard Time)

java.util.Date类

  • Date类表示特定的瞬间,精确到毫秒,线程不安全
构造器描述
Date()使用无参构造器创建的对象可以获取本地当前时间
Date(long date)有参构造器根据毫秒值创建指定时间的对象
常用方法描述
getTime()返回自1970年1月1日00:00:00 GMT以来此Date对象表示的毫秒数
void setTime(long time)修改为指定毫秒值指定时间的对象
toString()把此Date对象转换为以下形式的String:dow mon dd hh:mm:ss zzz yyyy,其中dow是一周中的某一天(Sun, Mon, Tue, Wed, Thu, Fri, Sat),zzz是时间标准
boolean after(Date when)判断当前对象是否在when对象之后
boolean before(Date when)判断当前对象是否在when对象之前
Object clone()深克隆
int compareTo(Date anotherDate)比较方法 返回-1、0、1
  • 其它很多方法都过时了

java.text.SimpleDateFormat类

  • Date类的API不易于国际化,大部分被废弃了,SimpleDateFormat类是一个不与语言环境有关的方式来格式化和解析日期的具体类(负责日期格式化)
  • SimpleDateFormat类允许进行 格式化日期→文本解析文本→日期
构造器描述
SimpleDateFormat()创建对象使用默认的格式和语言环境,例:21-4-26 下午4:47
SimpleDateFormat(String pattern)创建对象使用参数pattern格式日期与解析文本
SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols)使用给定的模式和日期格式符号构造SimpleDateFormat
SimpleDateFormat(String pattern, Locale locale)使用给定的模式和给定区域设置的默认日期格式符号构造SimpleDateFormat
常用方法描述
void applyLocalizedPattern(String pattern)将给定的本地化模式字符串应用于此日期格式 “aaaa-nn-jj”
void applyPattern(String pattern)将给定的模式字符串应用于此日期格式 “yyyy-MM-dd”
Object clone()深克隆
boolean equals(Object obj)重写了equals方法
StringBuffer format(@NotNull() Date date, @NotNull() StringBuffer toAppendTo, @NotNull() FieldPosition pos)将给定日期格式化为日期时间字符串,并将结果附加到给定StringBuffer
AttributedCharacterIterator formatToCharacterIterator(Object obj)格式化产生AttributedCharacterIterator的对象,可以使用返回的对象构建结果字符串
Date get2DigitYearStart()返回100年周期的开始日期,两位数的年份被解释为在范围内
DateFormatSymbols getDateFormatSymbols()获取此日期格式的日期和时间格式符号的副本
Date parse(@NotNull() String text, @NotNull() ParsePosition pos)解析给定字符串文本,以生成一个日期
void set2DigitYearStart(Date startDate)设置100年周期2位数字年将被解释为在用户指定的日期开始
void setDateFormatSymbols(DateFormatSymbols newFormatSymbols)设置此日期格式的日期和时间格式符号
String toLocalizedPattern()返回描述此日期格式的本地化模式字符串
String toPattern()返回描述此日期格式的模式字符串

DateFormatSymbols类的用法
SimpleDateFormat(String pattern, Locale locale)用法

在这里插入图片描述

class Test {
    public static void main(String[] args) {
        // 产生一个Date实例
        Date date = new Date();
        // 产生一个SimpleDateFormat格式化的实例
        SimpleDateFormat formater = new SimpleDateFormat();
        // 打印输出默认的格式
        String format = formater.format(date);
        // 21-4-20 上午9:11
        System.out.println(format);
        // 产生一个SimpleDateFormat格式化的实例
        SimpleDateFormat formater2 = new SimpleDateFormat("yyyy年MM月dd日 EEE HH:mm:ss");
        // 2021年04月20日 星期二 09:11:51
        System.out.println(formater2.format(date));

        try {
            // 实例化一个指定的格式对象
            // 将指定的日期解析后格式化按指定的格式输出
            Date date2 = formater2.parse("2008年08月08日 星期一 08:08:08");
            // Fri Aug 08 08:08:08 CST 2008
            System.out.println(date2);
        } catch (ParseException e) {
        	// ParseException:解析异常
            e.printStackTrace();
        }
    }
}

java.util.Calendar(日历)类

  • Calendar是一个抽象基类,主用用于完成日期字段之间相互操作的功能
  • 获取Calendar实例的方法
       使用Calendar.getInstance()方法得到java.util.GregorianCalendar实例对象
       调用它的子类GregorianCalendar的构造器
  • 一个Calendar的实例是系统时间的抽象表示,通过get(int field)方法来取得想要的时间信息。比如YEAR、MONTH、DAY_OF_WEEK、HOUR_OF_DAY 、 MINUTE、SECOND
方法描述
public void set(int field,int value)给定的日历字段设置为给定值
abstract public void add(int field, int amount)给定的日历字段 添加或减去指定的时间,基于日历的规则
public final Date getTime()返回一个Date对象,该对象表示此Calendar的时间值(与Epoch的毫秒偏移量)
public final void setTime(Date date)用给定的日期设置此日历的时间
  • 注意:
    获取月份时:一月是0,二月是1,以此类推,12月是11
    获取星期时:周日是1,周二是2 ,…,周六是7
class Test {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        // 从一个Calendar对象中获取Date对象
        Date date = calendar.getTime();
        // 使用给定的Date设置此Calendar的时间
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH, 8);
        System.out.println("当前时间日设置为本月开始8天后,时间是:" + calendar.getTime());
        calendar.add(Calendar.HOUR, 2);
        System.out.println("当前时间加2小时后,时间是:" + calendar.getTime());
        calendar.add(Calendar.MONTH, -2);
        System.out.println("当前日期减2个月后,时间是:" + calendar.getTime());
    }
}

JDK8中新日期时间API

java.time包API简单介绍

新日期时间API出现的背景
Calendar和Date面临的问题
   可变性:像日期和时间这样的类应该是不可变的(不可变的类,其对象是不可变的。不论对它进行怎样的改变操作,返回的对象都是新对象)
   偏移性:Date中的年份是从1900开始的,而月份都从0开始
   格式化:格式化只对Date有用,Calendar则不行
   线程安全型,它们都线程不安全;不能处理闰秒等
  • Java8吸收了Joda-Time的精华,新的java.time中包含了所有关于本地日(LocalDate)、本地时间(LocalTime)、本地日期时间(LocalDateTime)、时区(ZonedDateTime)和持续时间(Duration)的类
  • Date类新增toInstant()方法,用于把Date转换成新的表示形式,这些新增的本地化时间日期API 大大简化了日期时间和本地化的管理
新时间日期API描述
java.time包含值对象的基础包
java.time.chrono提供对不同的日历系统的访问
java.time.format格式化和解析时间和日期
java.time.temporal包括底层框架和扩展特性
java.time.zone包含时区支持的类

java.time.LocalDate、LocalTime、LocalDateTime

  • LocalDate、LocalTime、LocalDateTime 类是其中较重要的几个类,它们的实例是不可变的对象,分别表示使用ISO-8601日历系统的日期、时间、日期和时间。它们提供了简单的本地日期或时间,并不包含当前的时间信息,也不包含与时区相关的信息
  • LocalDate代表IOS格式(yyyy-MM-dd)的日期,可以存储生日、纪念日等日期
  • LocalTime表示一个时间,而不是日期
  • LocalDateTime是用来表示日期和时间的,这是一个最常用的类之一
  • ISO-8601日历系统是国际标准化组织制定的现代公民的日期和时间的表示法,也就是公历
方法描述
now() / now(ZoneId zone) /now(Clock clock)静态方法,根据当前时间创建对象/指定时区的对象
of(int year, Month month, int dayOfMonth)静态方法,根据指定日期/时间创建对象
public static LocalDate from(TemporalAccessor temporal)根据指定的时间获取本地日期
public static LocalDate parse(CharSequence text)文本字符串中获取一个实例
public static LocalDate parse(CharSequence text, DateTimeFormatter formatter)使用格式化程序解析文本,返回一个日期
public boolean isSupported(TemporalField field)检查指定字段是否受支持
public ValueRange range(TemporalField field)获取指定字段的有效值范围
public int get(TemporalField field)获取日期对象指定字段的值
public long getLong(TemporalField field)获取日期对象指定字段的值
public IsoChronology getChronology()获取该日期的年表
public Era getEra()获取在此日期适用的纪元
public boolean isLeapYear()检查该年是否为闰年
public int lengthOfMonth()返回由该日期表示的月份的长度
public int lengthOfYear()返回此日期所表示的年份的长度
getDayOfMonth()/getDayOfYear()获得月份天数(1-31) /获得年份天数(1-366)
getDayOfWeek()获得星期几(返回一个 DayOfWeek 枚举值)
getMonth()获得月份, 返回一个 Month 枚举值
getMonthValue() / getYear()获得月份(1-12) /获得年份
getHour()/getMinute()/getSecond()获得当前对象对应的小时、分钟、秒
public LocalDate with(TemporalAdjuster adjuster)返回此日期的调整后副本
withDayOfMonth()/withDayOfYear()/withMonth()/withYear()将月份天数、年份天数、月份、年份修改为指定的值并返回新的对象
plusDays(), plusWeeks(), plusMonths(), plusYears(),plusHours()向当前对象添加几天、几周、几个月、几年、几小时
minusMonths() / minusWeeks()/minusDays()/minusYears()/minusHours()从当前对象减去几月、几周、几天、几年、几小时
public <R> R query(TemporalQuery<R> query)使用指定的查询查询此日期
public Temporal adjustInto(Temporal temporal)调整指定的时间对象以使其日期与此对象相同
public long until(Temporal endExclusive, TemporalUnit unit)以指定的单位计算到另一个日期的时间量
public String format(DateTimeFormatter formatter)使用指定的格式化程序格式化此日期
public LocalDateTime atTime(LocalTime time)将LocalTime和LocalDate组合起来创建LocalDateTime
public LocalDateTime atStartOfDay()将此日期与’00:00’结合,在该日期的开始创建一个LocalDateTime
public long toEpochDay()距1970-01-01过了多少天
public int compareTo(ChronoLocalDate other)将这个日期与另一个日期进行比较
public boolean isAfter(ChronoLocalDate other)检查该日期是否在指定日期之后
public boolean isEqual(ChronoLocalDate other)检查此日期是否等于指定的日期
public int hashCode()重写了hashCode()方法
public String toString()重写了toString()方法

瞬时java.time.Instant

  • Instant:时间线上的一个瞬时点,可以用来记录应用程序中的事件时间戳
  • 处理时间和日期的时候,人通常会想到年、月、日、时、分、秒,机器可以处理时间线中的一个点,在UNIX中,这个数从1970年开始,以秒为的单位;同样的,在Java中,也是从1970年开始,但以毫秒为单位
  • java.time包通过值类型Instant提供机器视图,不提供处理人类意义上的时间单位。Instant表示时间线上的一点,而不需要任何上下文信息,例如,时区。概念上讲,它只是简单的表示自1970年1月1日0时0分0秒(UTC)开始的秒数。因为java.time包是基于纳秒计算的,所以Instant的精度可以达到纳秒级。
  • 1ns = 10-9s               1秒 = 1000毫秒 =106微秒=109纳秒
方法描述
public static Instant now()静态方法,返回默认UTC时区的Instant类的对象
public static Instant now(Clock clock)从指定的时钟获取当前时刻
public static Instant ofEpochSecond(long epochSecond)使用秒获取Instant的实例
public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment)静态方法,返回在1970-01-01 00:00:00基础上加上指定秒数和纳秒数之后的Instant类的对象
public static Instant from(TemporalAccessor temporal)使用temporal对象创建一个Instant的实例
public static Instant parse(final CharSequence text)从文本字符串中获取Instant实例,例如“2007-12-03T10:15:30.00Z”
public boolean isSupported(TemporalField field)检查指定字段是否受支持
public ValueRange range(TemporalField field)获取指定字段的有效值范围
public int get(TemporalField field)获取指定字段的值
public long getLong(TemporalField field)获取指定字段的值
public long getEpochSecond()获取来自1970-01-01T00:00:00Z的的秒数
public int getNano()获取纳秒数
public Instant with(TemporalAdjuster adjuster)返回此瞬间的调整后副本
public Instant with(TemporalField field, long newValue)返回此瞬间的副本,并将指定字段设置为新值
public Instant truncatedTo(TemporalUnit unit)返回此“瞬间”被截短到指定单元的副本
public Instant plus(TemporalAmount amountToAdd)返回添加了指定金额的当前时刻的副本
public Instant plus(long amountToAdd, TemporalUnit unit)返回添加了指定金额的当前时刻的副本
public Instant plusSeconds(long secondsToAdd)返回添加了指定金额的当前时刻的副本
public Instant plusMillis(long millisToAdd)返回此瞬间的副本,并添加指定的持续时间(以毫秒为单位)
public Instant minus(TemporalAmount amountToSubtract)返回当前时刻的副本,减去指定的金额
public R query(TemporalQuery query)使用指定的查询立即进行查询
public long until(Temporal endExclusive, TemporalUnit unit)以指定的单位计算到另一个瞬间的时间量
public Temporal adjustInto(Temporal temporal)调整指定的时间对象以获得这个瞬间
public OffsetDateTime atOffset(ZoneOffset offset)结合即时的偏移来创建一个OffsetDateTime
public ZonedDateTime atZone(ZoneId zone)将此瞬间与时区相结合,创建ZonedDateTime对象
public long toEpochMilli()返回1970-01-01 00:00:00到当前时间的毫秒数,即为时间戳
public int compareTo(Instant otherInstant)
public boolean isAfter(Instant otherInstant)
public boolean isBefore(Instant otherInstant)
public boolean equals(Object otherInstant)重写
public int hashCode()重写
public String toString()重写
  • 时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数

java.time.format.DateTimeFormatter格式化与解析日期或时间

DateTimeFormatter类提供了三种格式化方法
预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
本地化相关的格式。如:ofLocalizedDateTime(FormatStyle.LONG)
自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
方法描述
public static DateTimeFormatter ofPattern(String pattern)静态方法,返回一个指定字符串格式的DateTimeFormatter
public static DateTimeFormatter ofPattern(String pattern, Locale locale)使用指定的模式和区域设置创建格式化程序
public static DateTimeFormatter ofLocalizedDate(FormatStyle dateStyle)
public static DateTimeFormatter ofLocalizedDateTime(FormatStyle dateTimeStyle)
public Locale getLocale()获取格式化期间要使用的语言环境
public DateTimeFormatter withLocale(Locale locale)使用新的区域设置返回此格式化程序的副本
public String format(TemporalAccessor temporal)使用此格式化程序格式化日期-时间对象
public void formatTo(TemporalAccessor temporal, Appendable appendable)使用此格式化器将日期-时间对象格式化为Appendable
public TemporalAccessor parse(CharSequence text)将指定格式的字符序列解析为一个日期、时间
public TemporalAccessor parse(CharSequence text, ParsePosition position)使用此格式化程序解析文本,提供对文本位置的控制
public Format toFormat()以java.text.Format实例的形式返回此格式化程序

java.time.ZoneId

  • 该类中包含了所有的时区信息
  • 一个时区的ID,如Europe/Paris 或 GMT+2 或 UTC+01:00
  • ZoneId用于标识在Instant和LocalDateTime之间进行转换的规则
方法描述
public boolean equals(Object obj)检查此时区ID是否等于另一个时区ID
public static ZoneId from(TemporalAccessor temporal)从时态对象获取ZoneId的实例
public static Set<String> getAvailableZoneIds()获取可用区域ID的集合
public String getDisplayName(TextStyle style, Locale locale)获取区域的文本表示,例如:British Time或+02:00
public abstract String getId();获取唯一的时区ID
public abstract ZoneRules getRules();获取此ID的时区规则,允许执行计算
public int hashCode()此时区ID的哈希码
public ZoneId normalized()规范化时区ID,尽可能返回ZoneOffset
public static ZoneId of(String zoneId)从ID获取ZoneId的实例,确保该ID有效且可供使用
static ZoneId of(String zoneId, boolean checkAvailable)使用别名映射获取ZoneId的实例,以补充标准区域ID,checkAvailable检查zoneId是否可用
public static ZoneId of(String zoneId, Map<String, String> aliasMap)使用别名映射获取ZoneId的实例,以补充标准区域ID,别名区域id(通常是缩写)到实际区域id的映射,不能为空
public static ZoneId ofOffset(String prefix, ZoneOffset offset)获得包装偏移量的ZoneId实例
public static ZoneId systemDefault()获取系统默认时区
public String toString()使用ID将此区域输出为String

java.time.ZonedDateTime

  • ZonedDateTime:表示在ISO-8601日历系统时区的日期时间,如 2021-05-31T09:27:36.215+08:00[Asia/Shanghai]
  • 其中每个时区都对应着ID,地区ID都为“{区域}/{城市}”的格式,例如:Asia/Shanghai
方法描述
public boolean equals(Object obj)检查此日期时间是否等于另一个日期时间
public String format(DateTimeFormatter formatter)使用指定的格式化程序格式化此日期时间
public static ZonedDateTime from(TemporalAccessor temporal)从temporal对象获取ZonedDateTime的实例
public int get(TemporalField field)从此日期时间获取指定字段的int值
public int getDayOfMonth()获取月中的第几天
public DayOfWeek getDayOfWeek() / public int getDayOfYear() / public int getHour() / public long getLong(TemporalField field)
public int getMinute() / public Month getMonth() / public int getMonthValue() / public int getNano() / public ZoneOffset getOffset()
public int getSecond() / public int getYear() / public ZoneId getZone()
public int hashCode()此日期时间的哈希码
public boolean isSupported(TemporalField field) / public boolean isSupported(TemporalUnit unit)检查是否支持指定的字段
public ZonedDateTime minus(long amountToSubtract, TemporalUnit unit) / public ZonedDateTime minus(TemporalAmount amountToSubtract)返回此日期时间的副本,并减去指定的数量
public ZonedDateTime minusDays(long days)返回此ZonedDateTime的副本,并减去指定的天数
public ZonedDateTime minusHours(long hours) / public ZonedDateTime minusMinutes(long minutes) / public ZonedDateTime minusMonths(long months)
public ZonedDateTime minusNanos(long nanos) / public ZonedDateTime minusSeconds(long seconds) / public ZonedDateTime minusWeeks(long weeks) / public ZonedDateTime minusYears(long years)
public static ZonedDateTime now()从默认时区中的系统时钟获取当前日期时间
public static ZonedDateTime now(Clock clock)从指定的时钟获得当前日期时间
public static ZonedDateTime now(ZoneId zone)从指定时区的系统时钟获取当前日期时间
public static ZonedDateTime of(int year, int month, int dayOfMonth,int hour, int minute, int second, int nanoOfSecond, ZoneId zone)从年,月,日,小时,分钟,秒,纳秒和时区获得ZonedDateTime的实例
public static ZonedDateTime of(LocalDate date, LocalTime time, ZoneId zone)从日期和时间获取ZonedDateTime的实例
public static ZonedDateTime of(LocalDateTime localDateTime, ZoneId zone)从本地日期时间获取ZonedDateTime的实例
public static ZonedDateTime ofInstant(Instant instant, ZoneId zone)从Instant和区域ID获取ZonedDateTime的实例
public static ZonedDateTime ofInstant(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone)从通过组合本地日期时间和偏移量形成的瞬间获得ZonedDateTime的实例
public static ZonedDateTime ofLocal(LocalDateTime localDateTime, ZoneId zone, ZoneOffset preferredOffset)如果可能,使用首选偏移量从本地日期时间获取ZonedDateTime的实例
public static ZonedDateTime ofStrict(LocalDateTime localDateTime, ZoneOffset offset, ZoneId zone)获得ZonedDateTime的实例,严格验证本地日期时间,偏移量和区域ID的组合
public static ZonedDateTime parse(CharSequence text)从文本字符串中获取ZonedDateTime的实例,例如2007-12-03T10:15:30+01:00[Europe/Paris]
public static ZonedDateTime parse(CharSequence text, DateTimeFormatter formatter)使用特定格式化程序从文本字符串中获取ZonedDateTime的实例
public ZonedDateTime plus(long amountToAdd, TemporalUnit unit)返回此日期时间添加指定的数量的副本
public ZonedDateTime plus(TemporalAmount amountToAdd)返回此日期时间添加指定的数量的副本
public ZonedDateTime plusDays(long days)返回此ZonedDateTime添加指定的天数的副本
public ZonedDateTime plusHours(long hours)返回此ZonedDateTime添加指定的小时数的副本
public ZonedDateTime plusMinutes(long minutes)返回此ZonedDateTime添加指定的分钟数的副本
public ZonedDateTime plusMonths(long months)返回此ZonedDateTime并添加指定的月数的副本
public ZonedDateTime plusNanos(long nanos)返回此ZonedDateTime添加了指定的纳秒数的副本
public <R> R query(TemporalQuery<R> query)使用指定的查询查询此日期时间
…………

java.time.Clock

  • 使用时区提供对当前时刻、日期和时间的访问
  • 抽象类
  • 子类有四个内部类FixedClock、OffsetClock、SystemClock、TickClock
方法描述
public boolean equals(Object obj)检查此时钟是否等于另一个时钟
public static Clock fixed(Instant fixedInstant, ZoneId zone)获取始终返回同一时刻的时钟
public abstract ZoneId getZone()获取用于创建日期和时间的时区
public int hashCode()获取此时钟的哈希码
public abstract Instant instant()获取时钟的当前时刻
public long millis()该方法获得时钟的当前毫秒时刻
public static Clock offset(Clock baseClock, Duration offsetDuration)获取一个时钟,该时钟从指定的时钟返回时刻,并添加指定的持续时间
public static Clock system(ZoneId zone)使用最佳可用系统时钟获取返回当前时刻的时钟
public static Clock systemDefaultZone()使用最佳可用系统时钟获取返回当前时刻的时钟,使用默认时区转换为日期和时间
public static Clock systemUTC()使用最佳可用系统时钟获取返回当前时刻的时钟,使用UTC时区转换为日期和时间
public static Clock tick(Clock baseClock, Duration tickDuration)获取一个时钟,该时钟将截断的指定时钟的瞬间返回到指定持续时间的最近出现位置
public static Clock tickMinutes(ZoneId zone)使用最佳可用系统时钟获取一个时钟,该时钟以整分钟返回当前时刻
public static Clock tickSeconds(ZoneId zone)使用最佳可用系统时钟获取一个时钟,该时钟以整秒为单位返回当前时刻
public abstract Clock withZone(ZoneId zone)返回具有不同时区的此时钟的副本

其它API

class Test {
    public static void main(String[] args) throws java.time.DateTimeException {
        // 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);

        //Duration:用于计算两个时间间隔,以秒和纳秒为基准
        LocalTime localTime = LocalTime.now();
        LocalTime localTime1 = LocalTime.of(10, 30, 0);
        //between():静态方法,返回Duration对象,表示两个时间的间隔
        Duration duration = Duration.between(localTime1, localTime);
        System.out.println(duration);
        System.out.println(duration.getSeconds());
        // Gets the number of nanoseconds within the second in this duration
        System.out.println(duration.getNano());

        localDateTime = LocalDateTime.of(1998, 4, 24, 10, 0, 0);
        LocalDateTime localDateTime1 = LocalDateTime.of(2021, 4, 20, 10, 31, 32);
        Duration duration1 = Duration.between(localDateTime, localDateTime1);
        // 8397
        System.out.println(duration1.toDays());

        //Period:用于计算两个日期间隔,以年、月、日衡量
        LocalDate localDate = LocalDate.of(2021, 4, 20);
        LocalDate localDate1 = LocalDate.of(2022, 4, 20);
        Period period = Period.between(localDate, localDate1);
        // P1Y
        System.out.println(period);
        // 1
        System.out.println(period.getYears());
        // 0
        System.out.println(period.getMonths());
        // 0
        System.out.println(period.getDays());
        Period period1 = period.withYears(2);
        // P2Y
        System.out.println(period1);

        // TemporalAdjuster:时间校正器
        // 获取当前日期的下一个周日是哪天?
        TemporalAdjuster temporalAdjuster = TemporalAdjusters.next(DayOfWeek.SUNDAY);
        LocalDateTime localDateTime2 = LocalDateTime.now().with(temporalAdjuster);
        System.out.println(localDateTime2);
        // 获取下一个工作日是哪天?
        LocalDate localDate2 = 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("下一个工作日是:"+ localDate2);
    }
}

Java8新日期时间API与传统日期API的转换

旧->新新->旧
java.time.Instant与java.util.DateDate.from(instant)date.toInstant()
java.time.Instant与java.sql.TimestampTimestamp.from(instant)timestamp.toInstant()
java.time.ZonedDateTime与java.util.GregorianCalendarGregorianCalendar.from(zonedDateTime)cal.toZonedDateTime()
java.time.LocalDate与java.sql.TimeDate.valueOf(localDate)date.toLocalDate()
java.time.LocalTime与java.sql.TimeDate.valueOf(localDate)date.toLocalTime()
java.time.LocalDateTime与java.sql.TimestampTimestamp.valueOf(localDateTime)timestamp.toLocalDateTime()
java.time.ZoneId与java.util.TimeZoneTimezone.getTimeZone(id)timeZone.toZoneId()
java.time.format.DateTimeFormatter与java.text.DateFormatformatter.toFormat()

Java比较器

Java中经常会涉及到存放对象的数组、集合的排序问题,那么就涉及到对象之间的比较问题,Java实现对象排序的方式有两种
自然排序:java.lang.Comparable
定制排序:java.util.Comparator

java.lang.Comparable接口自然排序

  • 实现Comparable的类必须重写compareTo(Object obj)方法,两个对象即通过compareTo方法的返回值来比较大小。如果当前对象this大于形参对象obj,则返回正整数,如果当前对象this小于形参对象obj,则返回负整数,如果当前对象this等于形参对象obj,则返回0
  • 实现Comparable接口的对象列表和数组可以通过Collections.sort()或Arrays.sort()进行自动排序。实现此接口的对象可以用作有序映射TreeMap中的键或有序集合TreeSet中的元素,无需指定比较器
  • 对于类的两个对象,当且仅当compareTo()返回值与equals()返回值有关时,类的自然排序才叫做与equals一致,建议(虽然不是必需的)最好使自然排序与 equals一致
  • Java中的有序集合
Comparable的典型实现:(默认都是从小到大排列)
1.String:按照字符串中字符的Unicode值进行比较
2.Character:按照字符的Unicode值来进行比较
3.数值类型对应的包装类以及BigInteger、BigDecimal:按照它们对应的数值大小进行比较
4.Boolean:true对应的包装类实例大于false对应的包装类实例
5.Date:后面的日期时间比前面的日期时间大
class Goods implements Comparable<Goods> {
    private String name;
    private double price;

    public Goods(String name, double price) {
        this.name = name;
        this.price = price;
    }

    // getter、setter方法略
	// toString()方法

    //按照价格,比较商品的大小
    @Override
    public int compareTo(Goods other) {
        if (this.price > other.price) {
            return 1;
        } else if (this.price < other.price) {
            return -1;
        }
        return 0;
    }
}

class ComparableTest {
    public static void main(String[] args) {
        Goods[] all = new Goods[4];
        all[0] = new Goods("《红楼梦》", 100);
        all[1] = new Goods("《西游记》", 80);
        all[2] = new Goods("《三国演义》", 140);
        all[3] = new Goods("《水浒传》", 120);
        Arrays.sort(all);
        System.out.println(Arrays.toString(all));
    }
}

java.util.Comparator接口定制排序

  • 当元素的类型没有实现java.lang.Comparable接口而又不方便修改代码,或者实现了java.lang.Comparable接口的排序规则不适合当前的操作,那么可以考虑使用Comparator的对象来排序,强行对多个对象进行整体排序的比较
  • 重写compare(Object o1,Object o2)方法,比较o1和o2的大小:如果方法返回正整数,则表示o1大于o2;如果返回0,表示相等;返回负整数,表示o1小于o2
  • 可以将Comparator对象传递给sort()方法,从而允许在排序顺序上实现精确控制
  • 可以使用Comparator来控制某些数据结构(如有序Set或有序映射)的顺序,或者为那些没有自然排序的对象集合提供排序
class ComparableTest {
    public static void main(String[] args) {
        Goods[] all = new Goods[4];
        all[0] = new Goods("War and Peace", 100);
        all[1] = new Goods("Childhood", 80);
        all[2] = new Goods("Scarlet and Black", 140);
        all[3] = new Goods("Notre Dame de Paris", 120);
        Arrays.sort(all, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Goods g1 = (Goods) o1;
                Goods g2 = (Goods) o2;
                return g1.getName().compareTo(g2.getName());
            }
        });
        System.out.println(Arrays.toString(all));
    }
}

System类

  • System类代表系统,系统级的很多属性和控制方法都放置在该类的内部。该类位于java.lang包内
  • 由于该类的构造器是private的,所以无法创建该类的对象,也就是无法实例化该类。其内部的成员变量和成员方法都是static,可以方便的调用
成员变量
System类内部包含in、out和err三个字节流成员变量,分别代表标准输入流(键盘输入),标准输出流(显示器)和标准错误输出流(显示器)
成员方法描述
public static native void arraycopy(Object src, int srcPos,Object dest, int destPos,int length)将src数组数据复制到dest数组中
public static String clearProperty(String key)删除由指定键指示的系统属性
public static Console console()返回与当前Java虚拟机关联的唯一Console对象
public static native long currentTimeMillis()返回当前的计算机时间,时间的表达格式为当前计算机时间和GMT时间(格林威治时间)1970年1月1号0时0分0秒所差的毫秒数
public static void exit(int status)终止当前运行的Java虚拟机。status参数为0代表正常退出,非零代表异常终止。使用该方法可以在图形界面编程中实现程序的退出功能等
public static void gc()该方法的作用是请求系统进行垃圾回收。至于系统是否立刻回收,则取决于系统中垃圾回收算法的实现以及系统执行时的情况
public static java.util.Map<String,String> getenv()获取OS的系统环境变量
public static String getenv(String name)获取OS的系统环境变量
public static Properties getProperties() / public static String getProperty(String key) / public static String getProperty(String key, String def)获得系统中属性名为key的属性对应的值。系统中常见的属性名以及属性的作用如下表所示:在这里插入图片描述
public static SecurityManager getSecurityManager()获取系统安全接口
public static native int identityHashCode(Object x)返回对象精确的hashCode值,根据该对象的地址计算得到的hashCode值
public static Channel inheritedChannel() throws IOException返回创建当前JVM实体继承的通道
public static String lineSeparator()返回与系统相关的行分隔符字符串
public static void load(String filename)加载由filename参数指定的本机库代码,filename参数必须是绝对路径名
public static void loadLibrary(String libname)加载由libname参数指定的本机库
public static native String mapLibraryName(String libname)将库名 映射到 表示本机库的特定于平台的字符串
public static native long nanoTime()返回JVM时间源的当前值(以纳秒为单位)
public static void runFinalization()运行处于挂起终止状态的所有对象的终止方法
public static void setErr(PrintStream err)重新分配“标准”错误输出流
public static void setIn(InputStream in)重新分配“标准”输入流
public static void setOut(PrintStream out)重新分配“标准”输出流
public static void setProperties(Properties props)将系统属性设置成Properties参数
public static String setProperty(String key, String value)设置指定键的系统属性
public static void setSecurityManager(final SecurityManager s)设置系统安全性
class Test {
    public static void main(String[] args) throws java.time.DateTimeException {
        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);
    }
}

Math类

  • java.lang.Math类提供了一系列静态方法用于科学计算
  • Math类 API

构造方法描述
private Math() {}私有的构造方法
常用方法描述
public static double abs(double/float/int/long)绝对值
acos(double),asin(double),atan(double),cos(double),sin(double),tan(double)(反)三角函数
public static double atan2(double y, double x)从直角坐标x, y到极坐标的转换返回角度
public static int addExact(int x, int y)/public static long addExact(long x, long y)返回参数的和
public static double cbrt(double a) a 3 \sqrt[3]{a} 3a
public static double ceil(double a)向上取整
public static double copySign(double magnitude, double sign) / public static float copySign(float magnitude, float sign)返回第一个浮点参数,并带有第二个浮点参数的符号
public static double cosh(double x)返回双精度值的双曲余弦值
public static int decrementExact(int a) / public static long decrementExact(long a)返回减1的实参
public static double exp(double a)e为底指数,返回ea
public static double expm1(double x)返回ex-1
public static double floor(double a)向下取整
public static int floorDiv(int x, int y) / public static long floorDiv(long x, long y)先x/y,再向下取整
public static int floorMod(int x, int y) / public static long floorMod(long x, long y)x - floorDiv(x, y) * y,即x/y的余数
public static int getExponent(double/float)返回参数的无偏指数
public static double hypot(double x, double y) x 2 + y 2 \sqrt{x^{2}+y^{2}} x2+y2
public static double IEEEremainder(double f1, double f2)计算IEEE 754标准的两个参数的余数运算
public static int incrementExact(int/long)参数加1
public static double log(double a) log ⁡ e a \log_ea logea
public static double log1p(double x) log ⁡ e ( x + 1 ) \log_e(x+1) loge(x+1)
public static double log10(double a) lg ⁡ a \lg a lga
public static double max(double a, double b) / public static float max(float a, float b) / public static int max(int a, int b) / public static long max(long a, long b)返回两个双精度值中的较大值
public static double min(double a, double b)返回两个双精度值中较小的一个
public static int multiplyExact(int x, int y) / public static long multiplyExact(long x, long y)x与y的乘积
public static int negateExact(int/long)a的取反值
public static double nextAfter(double start, double direction) / public static float nextAfter(float start, double direction)返回(direction方向)相邻start的浮点数
public static double nextDown(double d) / public static float nextDown(float f)返回在负无穷方向上与参数相邻的浮点值
public static double nextUp(double d) / public static float nextUp(float f)返回在正无穷方向上与参数相邻的浮点值
public static double pow(double a, double b) a b a^{b} ab
public static double random()返回一个[0.0,1.0)的双精度值
public static double rint(double a)返回与参数值最接近且等于整数的double值
public static long round(double a) / public static int round(float a)返回最接近参数的整数,即四舍五入
public static double scalb(double d, int scaleFactor) / public static float scalb(float f, int scaleFactor) a ∗ 2 s c a l e F a c t o r a*2^{scaleFactor} a2scaleFactor
public static double signum(double d) / public static float signum(float f)Sgn()函数;参数为0时为0,参数大于0时为1.0,参数小于0时为-1.0
public static double sinh(double x)返回双精度值的双曲正弦值
public static double sqrt(double a) a \sqrt{a} a
public static int subtractExact(int x, int y) / public static long subtractExact(long x, long y) x − y x - y xy
public static double tanh(double x)返回双精度值的双曲正切
public static double toDegrees(double angrad)将以弧度测量的角度转换为以度测量的近似等效角度,弧度转角度
public static int toIntExact(long value)(int)value
public static double toRadians(double angdeg)angdeg / 180.0 * PI,角度转弧度
public static double ulp(double/float )返回参数的ulp的大小。ulp是最后一个单位。float或double值的ulp是给定值与大小较大的下一个值之间的正距离

java.math.BigInteger与java.math.BigDecimal

  • Integer类作为int的包装类,能存储的最大整型值为231-1
  • Long包装类也是有限的,最大为263-1,如果要表示再大的整数,不管是基本数据类型还是他们的包装类都无能为力
  • java.math包的BigInteger可以表示不可变的任意精度的整数。BigInteger提供所有Java的基本整数操作符的对应物,并提供java.lang.Math的所有相关方法。另外,BigInteger还提供以下运算:模算术、GCD 计算、质数测试、素数生成、位操作以及一些其他操作
  • JDK1.1版本发行BigInteger
  • BigInteger常用API

构造器描述
public BigInteger(byte[] val)byte数组每位元素转二进制然后拼接再转换成BigInteger对象
public BigInteger(int signum, byte[] magnitude)byte数组每位元素转二进制然后拼接再转换成BigInteger对象,signum代表了数字的正负
public BigInteger(int bitLength, int certainty, Random rnd)构造一个[2numBits-1,2numBits]随机生成的BigInteger,根据certainty确定是质数概率
public BigInteger(int numBits, Random rnd)构建[0,2numBits-1]范围内的随机BigInteger
public BigInteger(String val)根据字符串构建BigInteger对象
public BigInteger(String val, int radix)根据字符串构建10进制BigInteger对象,val字符串是radix进制数据
常用方法描述
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) a b a^{b} ab
  • 一般的Float类和Double类可以用来做科学计算或工程计算,但在商业计算中,要求数字精度比较高,故用到java.math.BigDecimal类
  • BigDecimal类支持不可变的、任意精度的有符号十进制定点数
  • JDK1.5版本发行BigDecimal
  • 总是使用compareTo()比较两个BigDecimal的值,不要使用equals()
  • Java.math.BigDecimal类API

构造器描述
public BigDecimal(BigInteger val)将BigInteger转换为BigDecimal
public BigDecimal(BigInteger unscaledVal, int scale)将BigInteger转换为BigDecimal,BigInteger后scale位为小数部分
public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc)将BigInteger转换为BigDecimal,BigInteger后scale位为小数部分,并根据上下文设置进行舍入
public BigDecimal(BigInteger val, MathContext mc)将BigInteger转换为BigDecimal,并根据上下文设置进行舍入
public BigDecimal(char[] in)字符数组转换为BigDecimal,字符为数字
public BigDecimal(char[] in, int offset, int len)字符数组转换为BigDecimal,字符为数字,offset为转换开始的地方,len为长度
public BigDecimal(char[] in, int offset, int len, MathContext mc)字符数组转换为BigDecimal,字符为数字,offset为转换开始的地方,len为长度,并根据上下文设置进行舍入
public BigDecimal(char[] in, MathContext mc)字符数组转换为BigDecimal,字符为数字,并根据上下文设置进行舍入
public BigDecimal(double val)double转换为BigDecimal,该BigDecimal是double的二进制浮点值的精确十进制表示形式
public BigDecimal(double val, MathContext mc)double转换为BigDecimal,该BigDecimal是double的二进制浮点值的精确十进制表示形式,并根据上下文设置进行舍入
public BigDecimal(int val)将int转换为BigDecimal
public BigDecimal(int val, MathContext mc)将int转换为BigDecimal,并根据上下文设置进行舍入
public BigDecimal(long val)将long转换为BigDecimal
public BigDecimal(long val, MathContext mc)将long转换为BigDecimal,,并根据上下文设置进行舍入
public BigDecimal(String val)字符串转换为BigDecimal
public BigDecimal(String val, MathContext mc)将BigDecimal的字符串表示形式转换为BigDecimal,并根据上下文设置进行舍入
常用方法描述
public BigDecimal add(BigDecimal augend)
public BigDecimal subtract(BigDecimal subtrahend)
public BigDecimal multiply(BigDecimal multiplicand)
public BigDecimal divide(BigDecimal divisor)
public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)scale:保留几位小数;roundingMode:保留模式。常用保留模式有:ROUND_UP:直接进位、ROUND_DOWN:直接舍去、ROUND_HALF_UP:四舍五入、ROUND_HALF_DOWN:>5进位,<=5舍去
class Test {
    public static void main(String[] args) throws java.time.DateTimeException {
        BigInteger bi = new BigInteger("12433241123");
        System.out.println(bi);
        BigDecimal bd1 = new BigDecimal("12435.351");
        BigDecimal bd2 = new BigDecimal("11");
        // java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
        // System.out.println(bd1.divide(bd2));
        // BigDecimal.ROUND_HALF_UP 舍入模式
        System.out.println(bd1.divide(bd2, BigDecimal.ROUND_HALF_UP));
        System.out.println(bd1.divide(bd2, 15, BigDecimal.ROUND_HALF_UP));
    }
}

面试题

1.运行结果

class StringTest {
    String str = new String("good");
    char[] ch = {'t', 'e', 's', 't'};

    public void change(String str1, char ch1[]) {
        str1 = "test ok";
        ch1[0] = 'b';
    }

    public static void main(String[] args) {
        StringTest ex = new StringTest();
        ex.change(ex.str, ex.ch);
        // good and
        System.out.print(ex.str + " and ");
        // best
        System.out.println(ex.ch);
    }
}

在这里插入图片描述
2.模拟一个trim方法,去除字符串两端的空格

    /* JDK */
    public String trim() {
    	// 字符串字符数组的长度
        int len = value.length;
        int st = 0;
        // 字符串字符数组
        char[] val = value;    /* avoid getfield opcode */

        while ((st < len) && (val[st] <= ' ')) {
            st++;
        }
        while ((st < len) && (val[len - 1] <= ' ')) {
            len--;
        }
        return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
    }

3.将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反转为abfedcg”

答案

    public String reverse3(String str, int start, int end) {
        StringBuffer s = new StringBuffer(str.length());
        s.append(str.substring(0, start));// ab
        for (int i = end; i >= start; i--) {
            s.append(str.charAt(i));
        }
        s.append(str.substring(end + 1));
        return s.toString();
    }

4.获取字符串A在字符串B中出现的次数

  • 思路一:遍历一遍字符串B,发现匹配时加1
  • 思路二:使用B的indexOf()方法,查询匹配的位置
  • 思路三:使用B的replace()方法,将字符串替换为空字符串后比较减少的长度

5.获取两个字符串中最大相同子串。提示:将短的那个串进行长度依次递减的子串与较长的串比较

	public String[] getMaxSameSubString1(String str1, String str2) {
		if (str1 != null && str2 != null) {
			StringBuffer sBuffer = new StringBuffer();
			String maxString = (str1.length() > str2.length()) ? str1 : str2;
			String minString = (str1.length() > str2.length()) ? str2 : str1;

			int len = minString.length();
			// i代表了要去几个字符
			for (int i = 0; i < len; i++) {
				for (int x = 0, y = len - i; y <= len; x++, y++) {
					String subString = minString.substring(x, y);
					if (maxString.contains(subString)) {
						sBuffer.append(subString + ",");
					}
				}
				System.out.println(sBuffer);
				if (sBuffer.length() != 0) {
					break;
				}
			}
			String[] split = sBuffer.toString().replaceAll(",$", "").split("\\,");
			return split;
		}

		return null;
	}

6.对字符串中字符进行自然顺序排序。提示:字符串变成字符数组,对数组排序,将排序后的数组变成字符串

7.运行结果

class Test {
    public static void main(String[] args) {
        String str = null;
        // super(16);
        StringBuffer sb = new StringBuffer();
        sb.append(str);
        // 4
        System.out.println(sb.length());
        // null
        System.out.println(sb);
        // super(str.length() + 16);
        // java.lang.NullPointerException
        StringBuffer sb1 = new StringBuffer(str);
    }
}

8.求两个日期之间相隔的天数

    public static void main(String[] args) {
        // 使用java.time.Period
        LocalDate from = LocalDate.of(2017,9,1);
        Period period = Period.between(from,LocalDate.now());
        System.out.println("2017-09-01到当前日期" + LocalDate.now());
        System.out.println("距离当前多少年:" + period.getYears());
        System.out.println("距离当前多少月:" + period.getMonths());
        System.out.println("距离当前多少日:" + period.getDays());

        // 使用java.time.temporal.ChronoUnit.DAYS
        LocalDate dateBefore = LocalDate.of(2017,9,1);;
        LocalDate dateAfter = LocalDate.of(2021,9,1);
        DAYS.between(dateBefore, dateAfter);

        // 使用java.time.Duration
        LocalDate today = LocalDate.now();
        LocalDate yesterday = today.minusDays(100);
        Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays();

        LocalDate from1 = LocalDate.of(2017, 9, 1);
        long day = LocalDate.now().toEpochDay() - from.toEpochDay();
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值