常用类和API

文章目录


本文字数较多,大家可以根据目录自行选取所需内容阅读

1. 包装类

众所周知Java中有八种基本数据类型,而我们说过Java中万事万物皆是对象,即Java中都是对引用数据类型的操作,如果我们想通过对象的形式去使用基本数据类型,就需要用到Java基本数据类型的包装类

1.1 基本数据类型的包装类

八种基本数据类型都有其对应的包装类,如下表

基本数据类型对应包装类
byteByte
shortShort
intInteger
longLong
floatFLoat
doubleDouble
charCharacter
booleanBoolean

可以看到,除了int 和 char 的包装类外,其他的包装类都是基本数据类型的首字母大写

包装类都来自java.lang包,其中整形和浮点型的包装类都继承自Number

classExtends1
1.2 包装类的常用成员和方法

以Integer为例,Integer中有以下常用成员

1.2.1常量:
MIN_VALUE//最小值
MAX_VALUE//最大值
1.2.2 double doubleValue()

将Integer类型的对象转为double类型

Integer i = 10;
double d = i.doubleValue();
System.out.println(d);

也可以通过xxxValue()的方法将Integer类型的对象转为xxx类型

1.2.3 int compareTo(Integer anotherInteger)

比较两个数大小

int i1 = i.compareTo(11);//i1大于i,返回1
int i2 = i.compareTo(9);//i2小于i,返回-1
System.out.println(i1);
System.out.println(i2);
1.2.4 boolean equals(Object obj)

判断两个数是否相等

 boolean b = i.equals(10);
 System.out.println(b);
1.2.5 static Integer valueOf(String s)

将字符串转为Integer对象

Integer integer = Integer.valueOf("12345");
System.out.println(integer + 1);//123456

但是在使用时我们需要注意,传入参数时只能传入数字字符串,否则会抛出NumberFormatException

1.2.6 String toString()

将数字转为字符串

Integer integer1 = 10;
System.out.println(integer1.toString() + 1);//101
1.2.7 static int parseInt(String s)

将字符串转为int类型

 int i3 = Integer.parseInt("1433222");
 System.out.println(i3+1);

与valueOf一样,使用时我们需要注意,传入参数时只能传入数字字符串,否则会抛出NumberFormatException

1.3 自动装箱和拆箱
1.3.1装箱

把一个基本数据类型转化为包装类就被称为装箱

以Integer为例,通过构造方法可以将一个int型转为Integer类型

Integer integer1 = new Integer(1);
Integer integer2 = Integer.valueOf(8);//通过valueOf可以将一个int型转为Integer类型
System.out.println(integer1);
System.out.println(integer2);
1.3.2拆箱

有装箱,就肯定有拆箱,把一个包装类转化为转化为基本数据类型就被称为拆箱

在Integer中,可以通过intValue方法把Integer类型转为int类型

int i = integer1.intValue();
System.out.println(i);
1.3.3 自动装箱和拆箱

jdk1.5中,引入了自动装箱和拆箱,可以直接进行基本数据类型和包装类的互相转化

Integer integer3 = 18;//自动装箱
int num = integer3;//自动拆箱

关于自动装箱和拆箱,有一些问题需要注意

Integer a = new Integer(127);
Integer b = new Integer(127);

Integer c = 127;
Integer d = 127;

Integer e = 128;
Integer f = 128;

System.out.println(a == b);//false
System.out.println(c == d);//true
System.out.println(e == f);//false

对于new的对象,因为是两个对象,所以a和b肯定不相等,这个没有疑问

使用自动装箱时,我们发现,数字是127时,c和d相等,但当数字超过127时,e == f却是false,说明e和f并不是一个对象

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
}

通过源码我们发现IntegerCache中缓存的是-128~127的常用数字,当数字是127时,自动装箱创建的是同一个对象,而数字超过127时,会新建对象,所以e==f为false

1.4 基本数据类型和字符串的转换
1.4.1字符串转基本数据类型

以int为例,字符串转int可以通过Integer提供的valueOf方法

 String str = "1433223";
 int num = Integer.valueOf(str);//通过valueOf转为Integer对象,再通过自动拆箱转为int
 System.out.println(num);

还可以通过Integer提供的parseInt方法

int num1 = Integer.parseInt(str);
System.out.println(num1);

在进行字符串转int时同样要注意NumberFormatException

1.4.2基本数据类型转字符串

以int为例,int转字符串可以通过以下几种方式

//1.拼接空字符串
int a = 10;
String str01 = a + "";

//2.使用Integer.toString()
int k = 100;
String str02 = Integer.toString(k);

//3.使用String.valueOf()
int t = 321;
String str03 = String.valueOf(321);
1.5 特殊包装类
1.5.1 BigInteger

Java中有两个特殊的包装类

其中第一个是用于计算超大数字的BigInteger,我们知道,即使是最大的long类型,也只能表示64bit的数据,但是BigInteger没有这些限制,我们可以让他等于一个非常大的数字:

BigInteger bigInteger = BigInteger.valueOf(Long.MAX_VALUE);
BigInteger bigInteger1 = bigInteger.pow(2);
BigInteger bigInteger2 = bigInteger.pow(8);
System.out.println(bigInteger);//9223372036854775807
System.out.println(bigInteger1);//85070591730234615847396907784232501249
System.out.println(bigInteger2);//52374249726338269874783614880766155793371912454611337886264179577532000370919343764787541041733925104025910035567032750922845842742640075519159173120001

通过上面代码我们可以看到,在进行一些特别大数字的运算时,我们可以使用BigInteger

BigInteger中提供了以下常用方法

//1.加法
BigInteger bigNum01 = new BigInteger("100");
BigInteger bigNum02 = bigNum01.add(bigNum01);
System.out.println(bigNum02);//200
//2.减法
BigInteger bigNum03 = bigNum02.subtract(new BigInteger("10"));
System.out.println(bigNum03);//190
//3.乘法
BigInteger bigNum04 = bigNum03.multiply(bigNum01);
System.out.println(bigNum04);//19000
//4.除法
BigInteger bigNum05 = bigNum04.divide(bigNum02);
System.out.println(bigNum05);//95
//幂次运算
BigInteger bigNum06 = bigNum05.pow(2);
System.out.println(bigNum06);//9025
1.5.2 BigDecimal

在进行大数字运算时我们可以使用BigInteger,在进行大数字超高精度的计算时,我们就可以使用BigDecimal

BigDecimal bigDecimal = new BigDecimal(10.0 / 3);
System.out.println(10.0 / 3);3.3333333333333335
System.out.println(bigDecimal);3.333333333333333481363069950020872056484222412109375

可以看到,BigDecimal的精度更高,可以进行小数点后更多位数的计算

BigDecimal的方法与BigInteger类似

//1.加法
BigDecimal bigNum01 = new BigDecimal(100);
BigDecimal bigNum02 = bigNum01.add(bigNum01);
System.out.println(bigNum02);//200
//2.减法
BigDecimal bigNum03 = bigNum02.subtract(new BigDecimal(10));
System.out.println(bigNum03);//190
//3.乘法
BigDecimal bigNum04 = bigNum03.multiply(bigNum01);
System.out.println(bigNum04);//19000
//4.除法
BigDecimal bigNum05 = bigNum04.divide(bigNum02);
System.out.println(bigNum05);//95
//幂次运算
BigDecimal bigNum06 = bigNum05.pow(2);
System.out.println(bigNum06);//9025

2. Math类

Math类中定义了一些常用的数学计算方法

2.1 Math类中的常用方法
方法说明
public static int abs(int a)返回参数的绝对值
public static double ceil(double a)返回大于或等于参数的最小double值,等于一个整数
public static double floor(double a)返回小于或等于参数的最大double值,等于一个整数
public static int round(float a)按照四舍五入返回最接近参数的int
public static int max(int a,int b)返回两个int值中的较大值
public static int min(int a,int b)返回两个int值中的较小值
public static double pow (double a,double b)返回a的b次幂的值
public static double random()返回值为double的正值,[0.0,1.0)
public static void main(String[] args) {

        System.out.println(Math.abs(-3));//3
        System.out.println(Math.ceil(3.14));//4.0
        System.out.println(Math.floor(3.14));//3.0
        System.out.println(Math.round(2.5));//3
        System.out.println(Math.max(2, 3));//3
        System.out.println(Math.min(2, 3));//3
        System.out.println(Math.pow(2, 3));//8
        System.out.println(Math.random());//0.7399451761733676
}

3. String类

String 类代表字符串,Java 程序中的所有字符串文字(例如“ikun”)都被实现为此类的实例。也就是说,Java 程序中所有的字符串,都是 String 类的对象

3.1 String类的特点

String类不可被继承,因为其被final修饰

字符串不可变,即创建后就不能修改

3.2 String类的构造方法
方法名说明
public String()创建一个空白字符串对象,不含有任何内容
public String(char[] charArr)根据字符数组的内容,来创建字符串对象
public String(byte[] byteArr)根据字节数组的内容,来创建字符串对象
String s = “xxx”;直接赋值的方式创建字符串对象,内容就是xxx
public class StringDemo01 {
    public static void main(String[] args) {
        //public String():创建一个空白字符串对象,不含有任何内容
        String s1 = new String();
        System.out.println("s1:" + s1);
        //public String(char[] charArr):根据字符数组的内容,来创建字符串对象
        char[] charArr = {'鸡', '你', '太', '美'};
        String s2 = new String(charArr);
        System.out.println("s2:" + s2);
        //public String(byte[] byteArr):根据字节数组的内容,来创建字符串对象
        byte[] byteArr = {72, 105, 44, 115, 111, 110,};
        String s3 = new String(byteArr);
        System.out.println("s3:" + s3);
        //String s = “abc”;    直接赋值的方式创建字符串对象,内容就是abc
        String s4 = "小黑子苏珊";
        System.out.println("s4:" + s4);
    }
}
3.3 String类对象的分析
		String s1 = "cherry";              // String 直接创建
        String s2 = "cherry";              // String 直接创建
        String s3 = s1;                    // 相同引用
        String s4 = new String("cherry");   // String 对象创建
        String s5 = new String("cherry");   // String 对象创建

        System.out.println(s1 == s2);//true
        System.out.println(s1 == s3);//true
        System.out.println(s4 == s5);//false
        System.out.println(s1 == s5);//false
        System.out.println(s1.equals(s5));//true
        System.out.println(s4.equals(s5));//true

当用String s1 = "cherry";方式创建字符串时,会先查找常量池是否有cherry,如果没有则创建,然后指向常量池中的cherry,如果有,则直接指向cherry

当使用关键字new创建字符串时,会在堆中开辟空间,指向堆中地址

1memoryAnalysis
3.4 String中的常用方法
3.4.1 int length()获取字符串长度
String str01 = "hello";
int length = str01.length();
System.out.println("字符串的长度是"+length);//字符串str01的长度是:5
3.4.2boolean equals(String str)判断字符串的内容是否一致
String str02 = "阿姨来一杯卡布奇诺";
String str03 = new String("阿姨来一杯卡布奇诺");
boolean bol = str02.equals(str03);
System.out.println(bol);//true
3.4.3char charAt(int index)返回指定索引处的char值
String str04 = "十七张牌你能秒我";
char c = str04.charAt(3);
System.out.println("str04索引3处的值:" + c);//str04索引3处的值:牌

通过charAt可以获取下标对应的字符

//使用charAt逆序遍历字符串
for (int i = str04.length() -1; i >= 0; i--) {
            System.out.print(str04.charAt(i));
}
3.4.4char[] toCharArray()将字符串转为字符数组
String str05 = "world";
char[] charArray = str05.toCharArray();
for (int i = 0; i < charArray.length; i++) {
    System.out.print(charArray[i]);
}
3.4.5String replace(char oldChar,char newChar)字符 替换
String str06 = "我干嘛";
String replaceStr = str06.replace('我', '你');
System.out.println(replaceStr);
3.4.6String replaceAll(String regex, String replacement)字符串替换
String str07 = "老八蜜汁臭豆腐";
String replaceAllStr = str07.replaceAll("臭豆腐", "小汉堡");
System.out.println(replaceAllStr);
3.4.7String[] split(String regex)字符串分隔
String str08 = "你看-这汉堡-做滴-行不行!";
String[] splitStr1 = str08.split("-");
System.out.println(Arrays.toString(splitStr1));
String[] splitStr2 = str08.split("-", 3);
System.out.println(Arrays.toString(splitStr2));
3.4.8String trim()去掉字符串前后的空格
String str09 = "   火鸡面,大辣椒,一顿不吃心刺挠  ";
String trimStr = str09.trim();
System.out.println(trimStr);
3.4.9String substring(int beginIndex,int endIndex)返回一个子字符串
String str10 = "全体起立,所有人给我站起来!";
String subStr1 = str10.substring(5);
System.out.println(subStr1);

String str11 = "--其实我比你想的更想你--";
String subStr2 = str11.substring(2, 12);
System.out.println(subStr2);
3.4.10boolean isEmpty()判断字符串是否为空
String str12 = "张三";
System.out.println(str12.isEmpty());
3.4.11String toLowerCase()将字符串转为小写
String str13 = "HELLO,WORLD";
String lowerStr = str13.toLowerCase();
System.out.println(lowerStr);
3.4.12String toUpperCase()将字符串转为大写
String str14 = "hello,world";
String upperStr = str14.toUpperCase();
System.out.println(upperStr);
3.4.13String valueOf(int i)将数字转为字符串
int a = 1433223;
String str = String.valueOf(a);
System.out.println(str);

4. StringBuilder && StringBuffer

StringBufferStringBuilder也是字符串类,里面包含了各种对字符串操作的方法

他们都继承自AbstractStringBuilder,不同于String,他们都是可变的字符串

StringBufferClassImage
4.1 常用方法(以StingBuilder为例)
4.1.1 StringBuilder append(String str)

字符串追加(可理解为字符串拼接),形参可以是字符串,字符,整数,浮点数

StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
sb1.append("你看这汉堡");
sb1.append("做滴");
sb1.append("行不行!");
System.out.println(sb1);//你看这汉堡做滴行不行!
sb2.append("你看这汉堡").append("做滴").append("行不行");//链式追加
System.out.println(sb2);//不吃好滴,不吃贵滴,今天整俩嘎嘣脆的
4.1.2 StringBuilder reserve()

字符串反转

StringBuilder sb3 = new StringBuilder("dlroW,olleH");
System.out.println(sb3.reverse());//Hello,World
4.1.3 StringBuilder delete(int start, int end)

删除索引范围内的字符串

StringBuilder deleteStr = sb3.delete(5, 11);
System.out.println(deleteStr);
4.1.4 AbstractStringBuilder insert(int offset, String str)

在指定索引处插入字符串

StringBuilder sb4 = new StringBuilder("火鸡面,一顿不吃心刺挠");
StringBuilder insertStr = sb4.insert(4, "大辣椒,");
System.out.println(insertStr);

此方法也可以插入字符,整数等

4.1.5 StringBuilder replace(int start, int end, String str)

用字符串替换指定索引范围内的字符串

StringBuilder replaceStr = sb4.replace(0, 3, "臭豆腐");
System.out.println(replaceStr);
4.2 String,StringBufferStringBuilder的区别

当对字符串进行修改的时候,需要使用 StringBuffer 和 StringBuilder 类,和 String 类不同的是,StringBuffer 和 StringBuilder 类的对象能够被多次的修改,并且不产生新的未使用对象。

虽然StringBuffer 和 StringBuilder功能类似,但是 StringBuffer是线程安全的,StringBuiler是线程不安全的

StringBuiler是线程不安全的,在速度上有优势,通常使用StringBuilder

long startTime = System.currentTimeMillis();//记录开始时间
StringBuilder sbStr = new StringBuilder("hello");
for (int i = 0; i < 1000000000; i++) {//执行1000000000次reverse方法
    sbStr.reverse();
}
long endTime = System.currentTimeMillis();//记录结束时间
System.out.println("StringBuilder执行了" + (endTime - startTime) + "毫秒");//StringBuilder执行了3941毫秒
long SbStartTime = System.currentTimeMillis();
StringBuffer sb = new StringBuffer("hello");
for (int i = 0; i < 1000000000; i++) {
    sb.reverse();
}
long SbEndTime = System.currentTimeMillis();
System.out.println("StringBuffer执行了" + (SbEndTime - SbStartTime) + "毫秒");//StringBuffer执行了20970毫秒

5. 时间日期

5.1 第一代日期类
5.1.1 Date

​ Date 类表示系统特定的时间戳,可以精确到毫秒。Date 对象表示时间的默认顺序是星期、月、日、小时、分、秒、年。

在使用Date类中创建对象时,有以下两种方式

Date date1 = new Date();
Date date2 = new Date(1000L);//调用有参构造,传入long 类型的值,表示毫秒值

当使用第二种方式创建对象时,时间会默认从格林威治时间(1970年0时0秒0分)开始

Date date1 = new Date();
Date date2 = new Date(1000L);
System.out.println(date1);//Tue Oct 11 23:57:06 CST 2022
System.out.println(date2);//Thu Jan 01 08:00:01 CST 1970

但是我们发现,date2时间是从1970年8时0分0秒开始的,这是因为我们处于东八区,比标准时间快八个小时

Date提供了以下方法

//1.boolean after(Date when) 判断该日期是否在指定日期之后
boolean isAfter = date1.after(date2);
System.out.println("date1在date2之后" + isAfter);//date1在date2之后:true

//2.boolean before(Date when) 判断该日期是否在指定日期之前
boolean isBefore = date1.before(date2);
System.out.println("date1在date2之前" + isBefore);//date1在date2之前:false

//3.int compareTo(Date anotherDate) 比较两个日期 大于:1,小于-1,等于:0
int i1 = date1.compareTo(date2);
int i2 = date2.compareTo(date1);
System.out.println(i1);//1
System.out.println(i2);//-1

//4.long getTime() 获取距1970年1月1日0时0分0秒的毫秒值
long time = date1.getTime();
System.out.println(time);//1665648932246

//5.String toString() 将日期转为字符串,形如EEE MMM dd HH:mm:ss zzz yyyy
String str = date1.toString();
System.out.println(str);//Thu Oct 13 16:15:32 CST 2022

5.1.2 SimpleDateFomat

SimpleDateFomat的作用是格式化日期,用户可以按照自己设定的规定对日期进行格式化

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss \n今天是今年第D天 这个月第dd天 E");
String formatDate = simpleDateFormat.format(new Date());
System.out.println(formatDate);
//2022-10-13 17:16:45
//今年第286天 这个月第13天 星期四

可以看到,通过指定yyyy-MM-dd HH:mm:ss的格式,就可以得到形如2022-10-13 17: 16: 45 格式的日期,

在格式化日期时,一些字母具有特定的含义

字母含义示例
y年份.有yy和yyyy两种格式yy:22 yyyy:2022
M月份.有MM和MMM两种格式MM:10 MMM:十月
m分钟数.一般用mm表示mm:10
D一年的第几天.用D表示D:286
d一个月的第几天.用dd表示dd:13
E星期几.用E表示E:星期四
H24小时制小时数.用HH表示HH:17
h12小时小时制.用hh表示hh:05
s秒数.用ss表示ss:50
S毫秒数.用SS表示SS:10
5.2 第二代日期类

在jdk1.1,出现了Calendar类,它是一个抽象类,

我们可以通过getInstance去获取Calendar的对象

Calendar calendar = Calendar.getInstance();
System.out.println(calendar);
//java.util.GregorianCalendar[time=1665668293289,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=29,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=9,WEEK_OF_YEAR=42,WEEK_OF_MONTH=3,DAY_OF_MONTH=13,DAY_OF_YEAR=286,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=38,SECOND=13,MILLISECOND=289,ZONE_OFFSET=28800000,DST_OFFSET=0]

我们可以发现,Calendar中有丰富的时间信息,但是这些信息很乱,很难去直观看出具体时间

所以Calendar提供了大量的字段和方法

//获取日历对象的某个日期字段,以2022年10月13日,21:54:54为例
//1.获取年份
int year = calendar.get(Calendar.YEAR);
System.out.println(year);//2022

//2.获取月份(在获取月份时默认从0开始,所以要加1)
int month = calendar.get(Calendar.MONTH);
System.out.println(month + 1);//10

//3.获取当月的天数
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(dayOfMonth);//13

//4.获取24小时制的小时数
int hourOfDay = calendar.get( Calendar.HOUR_OF_DAY);
System.out.println(hourOfDay);//21

//5.获取分钟数
int minute = calendar.get(Calendar.MINUTE);
System.out.println(minute);//54

//6.获取秒数
int second = calendar.get(Calendar.SECOND);
System.out.println(minute);//54

Calendar中并没有格式化日期的方法,所以需要我们进行灵活组合

 System.out.println("现在时间是");
 System.out.print(calendar.get(Calendar.YEAR) + "年" + calendar.get(Calendar.MONTH) + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "日");
 System.out.println(calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE) + ":" + calendar.get(Calendar.SECOND));
5.3 第三代日期类

在JDK1.8中,提供了LocalDate,LocalTime,LocalDateTime等新日期类,这些类是线程安全的

5.3.1 LocalDate

本地日期类

static LocalDate now()
    //获取当前日期
static LocalDate of(int year,int month,int dayOfMonth)
    //获取指定日期
    
    
public static void test() {
        LocalDate nowDate = LocalDate.now();
        System.out.println("当前日期时" + nowDate);
        LocalDate ofDate = LocalDate.of(1999, 10, 23);
        System.out.println("指定日期是" + ofDate);
}
5.3.2 LocalTime

本地时间类

static LocalTime now()
//获取当前时间
static LocalTime of(int hour, int minute, int second)
//获取指定时间
public static void main(String[] args) {
        LocalTime nowTime = LocalTime.now();
        System.out.println("现在时间是" + nowTime);
        LocalTime ofTime = LocalTime.of(18, 12, 30);
}
5.3.3 LocalDateTime

本地时间日期类

static LocalDateTime now()
 //获取当前日期和时间
static LocalDateTime of(LocalDate date,LocalTime time)
static LocalDateTime of(int year,int month,int dayOfMonth,...//时间信息)
//获取指定日期和时间
                        
public static void test1(){
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);
        LocalDateTime ofDatetime1 = LocalDateTime.of(LocalDate.of(1999, 10, 23), LocalTime.of(12, 20));
        System.out.println(ofDatetime1);
        LocalDateTime ofDatetime2 = LocalDateTime.of(2003, 5, 7, 12, 25);
        System.out.println(ofDatetime2);
}
                        
                        
getXXX()
//获取年份或月份...等信息
public static void test2() {
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("当前年份:" + localDateTime.getYear());
        System.out.println("当前月份:" + localDateTime.getMonthValue());
        System.out.println("当前几号:" + localDateTime.getDayOfMonth());
        System.out.println("当前小时:" + localDateTime.getHour());
        System.out.println("当前分钟:" + localDateTime.getMinute());
}  
                        
withXXX()
//修改日期
public static void test3(){
        LocalDateTime localDateTime = LocalDateTime.now();
        localDateTime = localDateTime.withYear(1999);
        localDateTime = localDateTime.withMonth(10);
        localDateTime = localDateTime.withDayOfMonth(23);
        System.out.println("修改后的日期"+localDateTime);
}                        
                        
plusXXX()
//增加
 public static void test4() {
        LocalDateTime localDateTime = LocalDateTime.now();
        localDateTime = localDateTime.plusDays(10);
        System.out.println("加10天后" + localDateTime);
}  
                        
minus()
//减少   
public static void test5(){
        LocalDateTime localDateTime = LocalDateTime.now();
        localDateTime = localDateTime.minusYears(23);
        System.out.println("减23年后:" + localDateTime);
}                                              
5.3.4 DateTimeFormatter

作用是格式化日期时间

public static void test() {
    LocalDateTime localDateTime = LocalDateTime.now();
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
    String format = dateTimeFormatter.format(localDateTime);
    System.out.println(format);
}
5.3.5 Instant

时间戳

提供了一系类和Date转换的方法

6. Arrays

Arrays其实就是进行数组处理的工具类,提供了很多对数组进行操作的方法,一般都是静态方法

6.1 static String toString(long[] a)

将数组转化为字符串

int[] arr = {1,2,3,4,5};
String str = Arrays.toString(arr);
System.out.println(str);
6.2 static void sort(int[] a)

对数组进行排序(快速排序)

int[] arr01 = {3, 1, 8, 5, 2, 7};
Arrays.sort(arr01);
System.out.println(Arrays.toString(arr01));
6.3 static int binarySearch(int[] a, int key)

二分查找,要求传入数组的必须有序

int[] arr02 = {1, 3, 4, 6, 7, 9};
int i = Arrays.binarySearch(arr02, 6);
System.out.println(i);
6.4 static int[] copyOf(int[] original, int newLength)

数组拷贝,将一个数组的值拷贝到另一个数组

int[] arr03 = Arrays.copyOf(arr02, 6);
for (int num : arr03) {
    System.out.print(num + " ");
}
6.5 static boolean equals(int[] a1, int[] a2)

比较两个数组的内容是否相等

 boolean b = arr03.equals(arr02);
 System.out.println(b);

7. System

7.1 成员变量
7.1.1 标准输出流

out

System.out.println("我是练习时长两年半的Java实习生");
7.1.2 标准输入流

in

Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
7.1.3 错误输出流

err

其语法与 System.out 类似,不需要提供参数就可输出错误信息。也可以用来输出用户指定的其他信息,包括变量的值

//例:输出字符串中的数字和字母,其他的用错误输出流输出
public static void test01() {
        String str = "h老八e蜜汁ll小汉堡o既实惠1又管饱23";
        char[] chars = str.toCharArray();
        for (char c : chars) {
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '1' && c <= '9')) {
                System.out.print(c);
            } else {
                System.err.print(c);
            }
        }
    }
7.2 成员方法
7.2.1 static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)

数组拷贝

7.2.2 static long currentTimeMillis()

系统时间距1970年0时0分0秒的毫秒值

long l = System.currentTimeMillis();
System.out.println(l);

通常我们可以用此方法去计算一段代码的执行时间

public static void test() {
    long startTime = System.currentTimeMillis();//获取开始时间
    int num = 0;
    for (int i = 0; i < 10000; i++) {
        for (int j = 0; j < 10000; j++) {
            num = j + i;
        }
    }
    long endTime = System.currentTimeMillis();//获取结束时间
    long time = endTime - startTime;//代码运行时间等于结束时间-开始时间
    System.out.println("代码执行时间为" + time + "毫秒");
}
7.2.3 static void exit(int status)

退出当前程序,当status为0时表示正常退出,非0表示异常退出

 public static void test(){
        System.out.println("程序开始执行-----");
        System.exit(0);
        System.out.println("程序结束执行-----");//不会执行此语句
    }
7.2.4 static void gc()

垃圾回收,调用该方法将请求JVM回收内存中的垃圾

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值