Java基础常用类&正则表达式

191 阅读8分钟

IDER快捷键

    alt + 回车   				代码提示

	ctrl + /;					单行注释/取消注释	
	ctrl + shift + /				多行注释/ 多行取消注释

	shift + 回车					   向下插入一行
	ctrl + alt + 回车				   向上插入一行
	ctrl + d;						快速复制一行
	ctrl + y;						快速删除一行


    ctrl + 鼠标左键               	  代码跟踪
	alt + 方向键左					  跟踪上一个方法
	alt + 方向键右					  跟踪下一个编辑处
	
	ctrl + shift + ↑				快速上移代码
	ctrl + shift + ↓				快速下移代码
		
	连续2shift					  查询jdk自带的类和自定义的类
	ctrl + f 						查找指定单词(可以替换指定的单词)
	ctrl + shift + u 			    将选中的全大写/ 将选中的全小写

	ctrl + o						查看继承的方法
	ctrl + i						查看实现的方法
	ctrl + h						查看继承关系
	ctrl + shift + h				查看子类
	
	alt + 7 						查看本类存在的方法
	ctrl + alt + L					快速格式化

	alt + insert                    自动生成代码

常用类

​ 【JDK对于一些开发中常用的工具/功能提前已经设计好了,对于开发人员直接使用】

​ 【开发中经常使用,得积累】

1.如何学习常用类

​ ①简单了解这个类是做什么的

​ ②快速浏览所有方法 有没有static修饰【是否要关注当前这个类里面的构造方法】

​ ③【关注构造方法,创建对象,调用非静态方法】

​ ④构造方法创建对象--无参,少量参数

​ ⑤调用方法的时候:

​ 形参列表:使用方法的时候要给他什么参数

​ 返回值类型:方法执行完功能以后,给什么内容

一.字符串String

​ Java

1.String :

【字符串是不可更改(修改 )的 是一个不可变的字符】

2.相关注意事项:

①null:产生异常是空指针异常

1691377685151转存失败,建议直接上传图片文件

​ ②java区间基本上是前闭后开

​ ③String转换字母大小写 可以用于验证码登录

​ ④打印语句会拖慢输出(节奏)进度 /效率

​ 省略了创建对象,节省内存

​ 拼接字符串使用

3.StringBuffer:

【保证线程安全,效率慢】

​ 可变的字符序列: StringBuffer是一个可变的字符串,当定义个字符串,以后无论拼接多少次,字符串始终是同一个地址

例如:

package com.ronghuanet._02String;

import com.sun.prism.shader.Solid_TextureYV12_AlphaTest_Loader;


public class StringSb {
    public static void main(String[] args) {
        /*
            //创建一个StringBuffer对象,里面的初始值是abc   相当于 new String("abc")
            StringBuffer sb = new StringBuffer("abc");
            StringBuffer def = sb.append("def");
            //StringBuffer sb2 =  sb+"yui";
            System.out.println(def);
            System.out.println(sb.hashCode());
            System.out.println(def.hashCode());
        */
        /*
            效率测试:
                String 出不来
                StringBuffer:63
                StringBuilder:46

         */
        StringBuilder s=new StringBuilder("");
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            //s+=i;
            s.append(i);
        }

        System.out.println(System.currentTimeMillis()-start);

    }
}

4.StringBuilder

【不保证线程的安全,再多线程的情况下,效率比StringBudder高】

二.常量池

【比较两个字符串是否相等equals方法】

设计思路为了节约内容,重复利用

注意事项:

String c = "abc"; 先检查常量池里是否有一样的字符串,如果有就返回原地址,如果没有就新增一个字符串

String f = new String(abc); 不会去检查常量池,会去堆空间创建对象

使用变量拼接都不会检查常量池,会直接在常量池里创建对象

例如:

public class StringTest2 {
    public static void main(String[] args) {

        String c ="abc";
        String d= "a"+"bc";//编译以后 就变成了"abc"
        String e= "abc";

        String f = new String("abc");
        String g = new String("abc");


        System.out.println(c==d);//true
        System.out.println(c==e);//true

        System.out.println(c==f);//false
        System.out.println(f==g);//false

        System.out.println(c.equals(f));//true
        System.out.println(g.equals(f));//true

    }
}

三.包装类

​ 基本数据类型:

​ 只能够描述当前范围内的一个值

1.包装类:

​ 不仅能够描述当前范围内的,还提供了对应数据的一些操作方法

基本数据类型包装类
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

1.1Integer(使用)

​ 构造方法:

​ Integer(int value) 构造一个新分配的 Integer对象,该对象表示指定的 int值。

​ Integer(String s) 构造一个新分配 Integer对象,表示 int由指示值 String参数。

​ 常用方法:

​ static Integer valueOf(int i) 返回一个 Integer指定的 int值的 Integer实例。

​ static Integer valueOf(String s) 返回一个 Integer对象,保存指定的值为 String 。

2.基本数据类型和包装类的区别

​ ①基本数据类型作为成员变量都有默认值,根据类型不同,值不同

​ ②包装类默认值都是null

​ ③基本数据类型不能调用方法,引用数据类型可以

例如:

public class IntegerTest {
    public static void main(String[] args) {
        String num="69";
        //需求:把num这个变量转换数字--》byte short int long
        Integer integer = new Integer(69);
        Integer integer2 = new Integer(num);

        System.out.println(integer+integer2);
        Integer integer1 = Integer.valueOf("96");
        Byte aByte = Byte.valueOf("69");
        Boolean aBoolean = Boolean.valueOf("true");
        System.out.println(aBoolean);

    }
}

3.valueOf

每一个包装类里面都有一个方法叫做valueOf------->都是可以将一个字符串换成对应的包装类

自动拆箱和自动装箱【jdk1.5后出的功能】

①自动装箱:

​ 把一个基本类型数据的值赋值给包装类的情况

②自动拆箱:

​ 把一个对象赋值给基本数据类型的行为

例如:

public class IntegerTest2 {
    public static void main(String[] args) {
        Integer integer = new Integer(69); // int i =69;
        Integer integer2 = new Integer(96);
        //JDK帮我们把 69封装为一个对象 再赋值给i这个变量
        Integer i = 69;
        Integer i2 = 96;
        //把integer这个对象里面的int值69取出来赋值给i3
        int i3=integer;
    }
}

4.享元模式:

【只要是引用数据类型比较,都应该使用equals】

​ 为了节约内容,提前把-128,127之间的数据缓存起来了,只要是定义在区间的数字都是使用缓存里面的数字

1691474992749转存失败,建议直接上传图片文件

例如:

public class IntegerTest3 {
    public static void main(String[] args) {
        // i1和 i2 都是引用的缓存里面的地址,所以是同一个地址
        Integer i1=127;
        Integer i2=128;
        
        //只要是new 就一定会去堆里面开辟内存存储数据
        Integer i3 = new Integer(127);
        Integer i4 = new Integer(128);

        System.out.println(i1==i2);//true
        System.out.println(i2==i3);//false
        System.out.println(i3==i4);//false

        System.out.println(i1.equals(i2));
        System.out.println(i3.equals(i2));
        System.out.println(i3.equals(i4));

        System.out.println(i4==128);


    }
}

四.Math

【数学的一些运算公式】

​ Math之后开发用的很少

​ static int abs(int a) 返回值为 int绝对值。

​ static double random() 返回值为 double值为正号,大于等于 0.0 ,小于 1.0 。[0.0,1.0)

例如:

public class MathTest {
    public static void main(String[] args) {
        System.out.println(Math.abs(-10));
        for (int i = 0; i < 10; i++) {
            System.out.println((int)(Math.random()*100+1));
        }
    }

}

1.BigInteger:

数字部分最大值Long就是上限 BigInteger(String val) 将BigInteger的十进制字符串表示形式转换为BigInteger。

例如:

public class BigIntegerTest {
    public static void main(String[] args) {
        long l = 9223372036854775807l;
        l=l+1;
        System.out.println(l);
        BigInteger bigInteger = new BigInteger("9223372036854775808");
        System.out.println(bigInteger);

    }
}

2.BigDecimal :

(float和double不能精确的表示一个小数)所以做系统的时候表示金钱类都必须使用

2.1BigDecimal(String val)

​ 将BigDecimal的字符串表示 BigDecimal转换为 BigDecimal 。

2.2BigDecimal(double val)

将 double转换为 BigDecimal ,这是 double的二进制浮点值的精确十进制表示。

例如:

public class BigDecimalTest {
    public static void main(String[] args) {
        //NaN  not a number
        // System.out.println(0.0/0.0);
        BigDecimal b1 = new BigDecimal("10.0");
        BigDecimal b2 = new BigDecimal("0.3");

        BigDecimal add = b1.add(b2);
        System.out.println(add);
        BigDecimal subtract = b1.subtract(b2);
        System.out.println(subtract);
        BigDecimal multiply = b1.multiply(b2);
        System.out.println(multiply);
        /*

            BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode)  返回一个 BigDecimal ,其值为 (this / divisor) ,其比例为指定。
            scale:保留几位小数
            RoundingMode:舍入的模式

         */
        BigDecimal divide = b1.divide(b2,3, RoundingMode.UP);
        System.out.println(divide);


    }
}

五.System类中的常用方法

1.Gc

​ [java中垃圾是自动回收的]

1.1System

​ static void gc()

​ 运行垃圾回收器。

1.2Runtime

​ void gc()

​ 运行垃圾回收器。

例如:

public class RunTimeTest {
    public static void main(String[] args) throws IOException {
        //接收当前类的对象
        Runtime runtime = Runtime.getRuntime();
        //运行dos命令--->只能去运行 C:\Windows\System32
        runtime.exec("ewnfjk");


    }
}

1.3Object

​ protected void finalize()

​ 当垃圾收集确定不再有对该对象的引用时,垃圾收集器在对象上调用该对象。

例如:

public class GcTest {
    public static void main(String[] args) {
        Person person = new Person();
        Person person1 = new Person();
        Person person2 = new Person();
        Person person3 = new Person();
        Person person4 = new Person();
        new Person();new Person();new Person();new Person();new Person();
        //不是百分百全部都回收干净
        System.gc();
    }

}
class Person{
    @Override
    public void finalize() throws Throwable {
        System.out.println( this+"被回收了");
    }
}

2.System

2.1.arraycopy

​ static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

将指定源数组中的数组从指定位置复制到目标数组的指定位置。

​ src:数据源

​ 【 第一个参数是要被复制的数组】

​ srcPos:从数据的哪个位置开始拷贝

​ 【第二个参数是被复制的数字开始复制下标

​ dest:目标,拷贝到那个数组去

​ 【第三个参数是目标数组,也就是要把数据放进来的数组】

​ destPos:在新数组的哪个位置开始放

​ 【第四个参数是从目标数据第几个下标开始放入数据

​ length:从数据源里面拷贝几个数据

​ 【第五个参数表示从被复制的数组中拿几个数值到目标数组中】

例如:


数组1:int[] arr = { 1, 2, 3, 4, 5 };
数组2:int[] arr2 = { 5, 6,7, 8, 9 };
运行:System.arraycopy(arr, 1, arr2, 0, 3);
得到:
int[] arr2 = { 2, 3, 4, 8, 9 };

2.2currentTimeMillis

​ static long currentTimeMillis()

​ 返回当前时间(以毫秒为单位)返回类型为long

​ 【用来获取当前的总毫秒数 】new Date()也是调用这个来实现的

例如:

public class SystemTest {
    public static void main(String[] args) {
        int[] arr = {4,1,66,1,68,64,16,10,6};

        int[] tar = new int[12];
        //从arr这个数组里的第0个位置开始拷贝 arr.length个数据到tar里面 从索引1的位置开始放
        System.arraycopy(arr,0,tar,1,3);

        System.out.println(Arrays.toString(tar));
        /*
            1691464293548 返回当前时间(以毫秒为单位)
                时间戳:1970-1-1 00:00:00:000ms 开始到当前的时间的计数


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

    }
}

六.获取随机数相关内容:

​ 【随机数使用场景-------验证码,游戏....】

方式一:【Math】

​ 里面有一个方法 获取0-1之间的随机数

方式二:【Random】

int nextInt() 生成 int的取值范围内的一个随机数

int nextInt(int bound) 返回伪随机的,均匀分布 int值介于0(含)和指定值(不包括),从该随机数生成器的序列绘制。

方式三:【ThreadLocalRandom】

static ThreadLocalRandom current() 返回当前线程的 ThreadLocalRandom

int nextInt(int origin, int bound) 返回指定原点(含)和指定边界(排除)之间的伪随机 int值。 [origin,bound)

方法码:【UUID】

​ static UUID randomUUID() 静态工厂检索一个类型4(伪随机生成)的UUID。

例如:

public class RandomTest {
    public static void main(String[] args) {
        //
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            System.out.println(random.nextInt(11));
        }

        ThreadLocalRandom current = ThreadLocalRandom.current();
        for (int i = 0; i < 6; i++) {
            System.out.print(current.nextInt(1, 34)+",");
        }
        System.out.println("-----------------------------------------");
        for (int i = 0; i < 10; i++) {
            System.out.println(UUID.randomUUID());
        }
    }

}

例如:

(随机数的应用)生成验证码的工具:

​ 1.可以去动态的配置生成几位数

//定义一个String方法
public static String getCode(int length){
        //1.验证码生成的范围
        String str="0123456789qwertyuiopas0123456789dfghjkl0123456789zxcvbnmQWERTYU0123456789IOPASDFG0123456789HJKLZXCVBNM";
        //2.把字符串转换为数组
        char[] chars = str.toCharArray();
        //3.循环4/6次,随机的从数组里面取值出来进行拼接,然后返回结果
        StringBuffer sb = new StringBuffer();
        ThreadLocalRandom l = ThreadLocalRandom.current();
        for (int i = 0; i < length; i++) {
            //随机取值
            char c= chars[l.nextInt(0,chars.length)];
            sb.append(c);
        }    

        return sb.toString();
    }

七.时间类 Date

​ 【表示时间的类】

1.Date( )

​ 分配一个Date的对象,并初始化它,以使代表它被分配的时间,测量到最近的毫秒

2.DateFormat

​ [时间格式化工具类]

​ SimpleDateFormat

​ SimpleDateFormat(String pattern) 使用给定模式 SimpleDateFormat并使用默认的 FORMAT语言环境的默认日期格式符号。

例如:

public class DateTest {
    public static void main(String[] args) {
        //创建当前时间
        Date date = new Date();
        System.out.println(date);
        //创建一个SimpleDateFormat对象并且指定时间的显示格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //把时间进行格式化
        String format = simpleDateFormat.format(date);
        System.out.println(format);
    }
}

八.异常:

异常处理:

1.异常继承体系:

​ Throwable

​ Error

Exception:

​ Exception有非常多的子类,这些子类没有过多的方法

java里面异常的类非常多,仅仅只是对代码运行出现错误的时候进行分类,方便编程人员排错

例如:

public class ThrowableTest {
    public static void main(String[] args) {
        String str=null;
       // char[] chars = str.toCharArray();//NullPointerException

     //   System.out.println(1/0);//ArithmeticException

        int[] arr = new int[10];
        System.out.println(arr[10]);//ArrayIndexOutOfBoundsException



    }
}

2.异常的处理方式:

2.1捕获异常:

​ try{

​ 可能发生异常的代码

​ }catch(异常类型 变量名 ){

​ 异常的处理语句

​ }

​ 或者

​ try{

​ 可能发生异常的代码

​ }catch(异常类型 变量名 ){

​ 异常的处理语句

​ }finally{

​ 最终要执行的语句

​ //无论是否发生什么 异常都会执行

​ }

写异常处理语句:

​ ①记录日志

​ ②获取异常的信息

​ ③打印堆栈信息 e.printStackTrace();

2.2抛出/抛异常:

​ 【本质:抛出异常本质就是不处理异常】

​ 修饰符 返回值类型 方法名(形参列表) throws 异常类型,异常类型{

​ }

例如:

 public static void main(String[] args) {
        /*
        try {

            int[] arr = new int[10];
           // System.out.println(arr[10]);//ArrayIndexOutOfBoundsException

            String str = null;
            char[] chars = str.toCharArray();//NullPointerException

            System.out.println(1 / 0);//ArithmeticException


        }catch (NullPointerException e){
            System.out.println("111111111");
        }catch (ArithmeticException e){
            System.out.println("22222222222");
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println("33333333333");
        }
         */
        try {

            int[] arr = new int[10];
            // System.out.println(arr[10]);//ArrayIndexOutOfBoundsException

            String str = null;
            //char[] chars = str.toCharArray();//NullPointerException

            System.out.println(1 / 0);//ArithmeticException

        }catch (Exception e){
            String message = e.getMessage();
            System.out.println("网络异常请稍后:"+message);
            e.printStackTrace();

        }finally {
            //无论是否发生异常都会执行--一般写关闭资源处理语句 --IO    JDBC
        }

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



    }

2.3自定义异常:

​ 用来新增一个异常类型,在系统中表示异常情况

步骤:

​ ①自己定义一个类,建议以Exception结尾

例如:

public class MyException extends RuntimeException{

    public MyException(){}
    //提示错误原因
    public MyException(String msg){
        super(msg);

    }

}

​ ②继承已知的异常类 建议:要么显示Exception 要么提示

​ ③一般提供一个无参构造和一个有参构造,里面都是调用父类的无参和有参构造,有参构造报错会提示错误原因,无参构造

​ throw 对外抛出一个异常对象

​ throws 定义在方法结构上面约束抛出类型

​ 只有在抛出RuntimeException或者RuntimeException的子类对象的时候 可以省略 throws语句

例如:

public class MyUtils {

    public static Date pares(String str) throws MyException{
        if (str==null||str.length()==0){
               throw  new MyException("参数不正确,str为空或者长度为0。请校准");
        }
        return new Date();
    }
}



public class Test {
    public static void main(String[] args) {
        Date pares = MyUtils.pares("");
    }
}

正则表达式

​ 【做匹配 做校验】

例如:

​ 手机号的验证:

​ 1.总共有11位

​ 2.第一位是1

​ 3.第二位是不能是0 1 2 4

String: boolean matches(String regex) 告诉这个字符串是否匹配给定的 regular expression 。*/

public class RegexpTest {
    public static void main(String[] args) {
        String phone="12008495702";
        boolean matches = phone.matches("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$");
        System.out.println(matches);
    }
}