• 人生苦短我学Java11常用类及方法 广深


    Java中有许多常用的类,比如时间日期、随机数、类型判断/转换。以下将是学习过程中记录的常用类及方法。

    一、引用类型:String

    1、什么是String?

    • 字符串
    • 字符串不变; 它们的值在创建后不能被更改(字符串是长度不可以改变字符序列)。
    • String是一个引用数据类型
    • 是jdk给我们提供好的一个现成的String类
    • "abc"既是一个字符串常量,也是一个字符串的对象(实例)

    在String中个人经常使用的是(不管任何语言),字符拼接、截断、替换、转换类型,判断是否包含字符串。如下:

    toString、equals

    // 二、【常用成员方法】
    // 指定索引获取对应的字符
    System.out.println("asd".charAt(0));
    // 按字典顺序比较两个字符串
    System.out.println("asd".compareTo("asd"));
    // concat 字符拼接,不会new stringBuffer 执行效率高
    System.out.println("asd".concat("123"));
    // 判断是否包含字符串
    System.out.println("asd".contains("sd"));
    // 将大写字母转换小写
    System.out.println("Axs".toLowerCase());
    // 将小写字母转换大写
    System.out.println("Axs".toUpperCase());
    // 比较两个字符串内容是否相等
    System.out.println("Axs".equals("Axs"));
    // 比较两个字符,不区分大小写
    System.out.println("Axs".equalsIgnoreCase("axs"));
    // 获取指定字符对应的索引值,如果找不到返回-1,只返回第一次找到的
    System.out.println("asd".indexOf('a'));
    System.out.println("asdb".indexOf('b'));
    //获取指定字符串对应的索引值,如果找不到返回-1,只返回第一次找到的
    System.out.println("asd".indexOf("s"));
    //获取指定字符串对应的索引值(返回最后一个,如果找不到返回-1
    System.out.println("asds".lastIndexOf("s"));
    // 判断字符串是否为空串
    System.out.println("asd".isEmpty());
    // 字符串长度
    System.out.println("asd".length());
    // 判断字符串是否是以指定字符开头
    System.out.println("asd".startsWith("sd"));
    System.out.println("asd".startsWith("as"));
    // 判断字符串是否是以指定字符结尾
    System.out.println("asd".endsWith("sd"));
    // 去除前后空格
    System.out.println(" a sd ".trim());
    // 获取字符串指定范围切片
    System.out.println("asd".substring(0, 3));
    System.out.println("asd".substring(1));
    // 分割字符串
    String[] sList = "a b c".split(" ");
    System.out.println(sList);
    // 替换字符串
    System.out.println("asdasdaasd".replace("asd", "das"));
    System.out.println("aaa".replaceAll("aa", "b"));
    // equals判断字符串是否相等
    System.out.println("123".equals("321"));
    // arr toString
    int[] arr = {4, 1, 68, 845, 54};
    arr = Arrays.copyOf(arr, 10);
    System.out.println(Arrays.toString(arr));
    String.format();
    String.join();

    2、常见的构造方法?

    • 1.public String():初始化一个新创建的 String 对象,使其表示一个空字符序列
    • 2.public String(byte[] bytes):将字节数组转换成字符串
    • 3.public String(byte[] bytes,int offset,int length):将字节数组的一部分转换成字符串
    • 4.public String(char[] value):将字符数组转换成字符串
    • 5.public String(char[] value,int offset,int count):将字符数组的一部分转换成字符串
    • 6.public String(String original):初始化一个新创建的 String 对象,使其表示一个与参数相同的字符序列
    • 7.String s = "abc";

    3、常见的成员方法?

    • 1.public char charAt(int index):获取指定索引对应的字符
    • 2.public int compareTo(String anotherString):按字典顺序比较两个字符串。
    • "abcde" -> {'a','b','c','d','e'}
    • "bccde" -> {'b','c','c','d','e'}
    • 对位比较,如果对位相等,去下一位再继续比
    • 3.public String concat(String str):字符串的拼接
    • 4.public boolean contains(String s):判断是否包含指定的字符串
    • 5.public String toLowerCase():将大写字母转换成小写字母
    • 6.public String toUpperCase():将小写字母转换成大写字母
    • 7.public boolean equals(Object anObject):比较两个字符串的内容是否一致
    • "abcde" -> {'a','b','c','d','e'} arr1[1]
    • "abcde" -> {'a','d','c','d','e'} arr2[1]
    • 8.public boolean equalsIgnoreCase(String anotherString):比较两个字符串的内容是否一致(不区分大小写)
    • 9.public int indexOf(int ch):获取指定字符对应的索引值,如果找不到返回-1
    • 10.public int indexOf(String str):获取指定字符串对应的索引值,如果找不到返回-1
    • 11.public int lastIndexOf(int ch):获取指定字符对应的最后第一次出现的位置的索引,如果找不到返回-1
    • 12.public boolean isEmpty():判断字符串是否为空串
    • 13.public int length():获取字符串的长度
    • 14.public boolean startsWith(String prefix):判断是否以指定的字符串为前缀的,开头
    • 15.public boolean endsWith(String suffix):判断是否以指定的字符串为后缀的,结尾
    • 16.public String replace(char oldChar,char newChar):替换字符
    • 17.public byte[] getBytes():将字符串转换成字节数组
    • 18.public char[] toCharArray():将字符串转换成字符数组
    • 19.public String trim():去除字符串的前后空格
    • 20.public String substring(int beginIndex):截取,从指定的索引开始截取到末尾
    • 21.public String substring(int beginIndex,int endIndex):
    • 截取,从指定的beginIndex索引开始截取到endIndex(包头不包尾)
    • 22.public String[] split(String regex):按照指定的符号进行切割,根据给定正则表达式的匹配拆分此字符串。
    • 正则表达式:是一个字符串,在字符串里面写一些规则,可以帮助对指定的String数据进行校验
    • 23.public String replace(String target,String replacement):替换子字符串

    String类型常见面试题:

    // 常见面试题
    /*
    1、通过new的string对象和直接复制的string对象有什么区别?
        new出来的,在内存中有2个对象(new string 和 "常量")
        通过赋值的对象,内存中只有1个对象("常量")
    */
    
    // 2、true 还是 false
    String a1 = "asd";
    String a2 = "asd";
    String a3 = new String("asd");
    System.out.println(a1 == a2);   // true
    System.out.println(a1 == a3);   // false
    
    // 3、
    String a4 = "as";
    String a5 = a4 + "d";           // asd
    System.out.println(a1 == a5);   // false 通过底层new stringBuffer
    
    // 4、
    String a6 = "as" + "d";
    System.out.println(a1 == a6);   // 都是在常量池的常量(常量优化机制),不会new新的对象

    二、StringBuffer

    1、什么是StringBuilder?

    • 一个可变的字符序列
    • 字符串缓冲区
    • 容器

    2、StringBuilder容器的特点?

    • 缓冲区可以装任何东西,但是装进去就取不出来了,而且装进去的数据都会变成字符串

    3、常见的构造方法?

    • public StringBuilder():构造一个不带任何字符的字符串生成器,其初始容量为 16 个字符。
    • public StringBuilder(String str):构造一个字符串生成器,并初始化为指定的字符串内容。

    4、常见的成员方法?

    • public StringBuilder append(任意类型 b):追加
    • public int capacity():返回当前容量
    • public StringBuilder reverse():反转
    • public String toString():将StringBuilder转换成String
    package com.ppl.object;
    /*
    com.ppl.object:学习项目
    @user:广深-小龙
    @date:2022/1/9 16:42
    */
    
    
    public class Ob3_jStringBuffer {
        public static void main(String[] args) {
            // 创建一个缓冲区,空串无值
            StringBuffer sb = new StringBuffer();
            System.out.println("1" + sb + "1");
    
            // 追加 append
            sb.append("str");
            sb.append('a');
            sb.append(123);
            sb.append(true);
            System.out.println(sb);
    
            // 动态扩容
            System.out.println(sb.capacity());          // 16
            sb.append("asd123asd456asd123asd456asd");
            System.out.println(sb.capacity());          // 38
    
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("abc_def_ghi");
            System.out.println(stringBuffer);
            // 反转
            stringBuffer.reverse();
            System.out.println(stringBuffer);
    
            // 将 String q 反转得到 String q="DSA"
            String q = "ASD";
            q = new StringBuffer(q).reverse().toString();
            System.out.println(q);
    
            // 将 string -> StringBuffer
            String t = "asd";
            StringBuffer sb1 = new StringBuffer(t);
            // 将 StringBuffer -> string
            sb1.toString();
    
        }
    }

    三、Math

    1、什么是Math?

    • Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。
    • 数学工具类,工具类:构造是私有的,成员方法是静态的。

    2、常见的成员方法?

    • public static int abs(int a):获取绝对值
    • public static int max(int a,int b):获取最大值
    • public static int min(int a,int b):获取最小值
    • public static double ceil(double a):向上取整
    • public static double floor(double a):向下取整
    • public static double pow(double a,double b):a的b次方
    • public static long round(double a):四舍五入
    • public static double random():返回带正数的 double 值,该值大于等于 0.0 且小于 1.0
    package com.ppl.object;
    /*
    com.ppl.object:学习项目
    @user:广深-小龙
    @date:2022/1/9 19:55
    */
    
    public class Ob4_ToolMath {
        /*
         工具类:
            构造是私有的
            成员方法是静态的
        */
        public static void main(String[] args) {
            // 绝对值
            System.out.println(Math.abs(-5));
            // 最大值
            System.out.println(Math.max(5, 3));
            // 最小值
            System.out.println(Math.min(5, 3));
            // 向上取整
            System.out.println(Math.ceil(10.1));
            // 向下取整
            System.out.println(Math.floor(10.1));
            // 3的2次方
            System.out.println(Math.pow(3,2));
            // 四舍五入
            System.out.println(Math.round(0.5));
            // 随机数
            System.out.println(Math.random());
            // 0-100
            System.out.println((int)(Math.random()*100));
            // 1-100
            System.out.println((int)(Math.random()*100+1));
        }
    }

    四、Integer

    1、什么是Integer类?

    • int基本数据类型对应的包装类

    2、常见的构造方法?
    public Integer(int value):

    • 1.创建Integer对象
    • 2.可以将int类型的数字转换成Integer类型的数子

    public Integer(String s):

    • 1.创建Integer对象
    • 2.可以将字符串格式的数字转换成Integer类型的数字

    3、常见的成员方法?

    • public boolean equals(Object obj):比较两个Integer类型的数字是否一样
    • public int intValue():将Integer类型转换成int类型的数据
    • *public static int parseInt(String s):将String类型的数字转换成int类型的数字
    • public String toString():将Integer类型转换String类型
    • public static String toString(int i):将int类型转换String类型
    • public static Integer valueOf(int i):将int类型转换Integer类型
    • public static Integer valueOf(String s):将String类型转换Integer类型
    public class Ob5_PakClass {
        public static void main(String[] args) {
            /*
            2.Integer,什么是Integer类?
            int基本数据类型对应的包装类
            */
            // 常见构造方法
            Integer i = new Integer(19);
            Integer s = new Integer("19");
            System.out.println(i); // 重写了toString,将int类型转换成Integer
            System.out.println(s); // 重写了toString,将string类型数字转换成Integer
            Integer ss = new Integer('a');
            System.out.println(ss);
    
    
            // 常用成员方法
            Integer s1 = 45;    // 自动装箱:Integer.valueOf(45)
            int o = s1;         // 自动拆箱:o.intValue()
            s1 = s1 + 3;        // 自动拆箱+装箱:Integer.valueOf(s1.intValue()+3)
            Integer s2 = new Integer("45");
            System.out.println(s1.equals(s2));
            // Integer转为int
            int in = s2.intValue();
            System.out.println(in);
            // 将string类型的数字转换成integer
            System.out.println(Integer.parseInt("123"));
            // 将integer转换为string
            System.out.println(s2.toString());
            // 将int转换为string
            System.out.println(Integer.toString(55));
            // int转为Integer
            System.out.println(Integer.valueOf(46));
    
            // 以下是ture还是false?
            Integer in1 = new Integer(127);
            Integer in2 = new Integer(127);
            System.out.println(in1 == in2);
    
            Integer in3 = new Integer(128);
            Integer in4 = new Integer(128);
            System.out.println(in3 == in4);
    
            Integer in5 = 127;
            Integer in6 = 127;
            System.out.println(in5 == in6);
            Integer in7 = 128;
            Integer in8 = 128;
            System.out.println(in7 == in8);     // false 通过静态内部类提供了一个缓存池,范围在-128~127之间,如果超过这个范围 Integer 值都是new出来的新对象
            // 那么我们该怎么比较不在-128~127之间的数据呢,可以使用equals判断,integer的equals方法重写了object里的equals,调用了intValue,比较两个对象的值。
        }
    }

    五、时间日期Date、Calendar、LocalDateTime

    建议使用jdk1.8新出的日期类:LocalDateTime

    Date与Calendar日常使用时间格式转换,如下代码:

    package com.ppl.object;
    /*
    com.ppl.object:学习项目
    @user:广深-小龙
    @date:2022/1/15 10:46
    */
    
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    
    public class Ob6_SysDate {
        public static void main(String[] args) throws ParseException {
    //        new MySystem().test();       // 1
    //        new MyDate().test();         // 2
    //        new MyDate().normal();       // 3
    //        new MyDay();
            new MyCalendar();
        }
    }
    
    // 时间相关建议使用:Calendar
    class MyCalendar {
        public MyCalendar() {
            Calendar c = Calendar.getInstance();
    
            // add 增加or减时间
            c.add(Calendar.HOUR, -10);
            System.out.println("add:" + c.get(Calendar.HOUR));
    
            // 获取getTime
            System.out.println("getTime():" + c.getTime());
    
            // 设置时间
            Calendar c1 = Calendar.getInstance();
            int day = c1.get(Calendar.DATE);
            System.out.println(day);
            c1.set(Calendar.DATE, day - 1);
            int day1 = c1.get(Calendar.DATE);
            System.out.println("修改后:" + day1);
    
            // 当前时间
            String nowTime = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + 1 + "-";
            nowTime = nowTime + c.get(Calendar.DAY_OF_MONTH) + " " + c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND);
            System.out.println(nowTime);
        }
    }
    
    // System类
    class MySystem {
        public void test() {
            // System 常用方法
    
            // System.currentTimeMillis 时间戳
            long timeMs = System.currentTimeMillis();
            System.out.println(timeMs); // 时间戳 ms
    
            // System.arraycopy 复制
            int[] arr = {1, 5, 465, 5};
            int[] arr1 = new int[4];
            // 从arr index 0开始复制到arr1的,0-4 index
            System.arraycopy(arr, 0, arr1, 0, 4);
            System.out.println();
            for (int i = 0; i < arr1.length; i++) {
                System.out.print(arr1[i] + " ");
            }
            System.out.println();
    
    
            // System.exit
            for (int i = 0; i < 10; i++) {
                if (i == 3) {
                    System.exit(0);
                    System.out.println(i);  // 程序结束了。不会执行到此
                }
                System.out.println(i);
            }
        }
    }
    
    // Date 类,很多方法已经是不建议使用
    class MyDate {
    
        public void normal() throws ParseException {
            // data --》 String: yyyy-MM-DD HH:mm:ss
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf1 = new SimpleDateFormat("E");      // 星期几?
            Date date = new Date();
            String nowTime = sdf.format(date);
            System.out.println(nowTime);
            System.out.println(sdf1.format(date));
    
            // string --》 data
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
            String newTime = nowTime;
            Date date1 = sdf2.parse(newTime);
            System.out.println(date1);
        }
    
        public void test() {
            // 空参构造 Sat Jan 15 12:54:56 CST 2022
            Date data = new Date();
            System.out.println(data);
    
            // LongTime 构造,传入时间戳
            long LongTime = System.currentTimeMillis();
            Date date1 = new Date(LongTime);
            System.out.println(date1);
    
            // 获取系统当前时间戳,data.getTime()
            System.out.println(data.getTime());
    
            // 设置当前时间戳为新的值
            data.setTime(1642222759937L);
            System.out.println(data.getTime());
        }
    }
    
    // 算一算自己目前为止在世上已经活了多少天
    class MyDay {
        public MyDay() throws ParseException {
            // 出生的年月日转换为时间戳
            String startYear = "2006-10-31";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            long startLong = sdf.parse(startYear).getTime();
    
            // (当前时间戳 - 出生时间戳)/1000/60/60/24
            Long nowDay = (new Date().getTime() - startLong) / 1000 / 60 / 60 / 24;
            System.out.println("你在世上已经活了:" + nowDay + "");
        }
    }

    重点掌握:LocalDateTime

    获取当前时间、指定时间,修改时间,字符串与LocalDateTime互相转换

    package com.ppl.object;
    /*
    com.ppl.object:学习项目
    @user:广深-小龙
    @date:2022/1/15 22:04
    */
    
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    
    public class Obj6_2LocalDateTime {
        public static void main(String[] args) {
            // jdk1.8新出的日期类
            // 当前时间
            LocalDateTime localDateTime = LocalDateTime.now();
            System.out.println("当前时间:" + localDateTime);
            // 指定时间
            LocalDateTime sendLocalDateTime = LocalDateTime.of(2022, 1, 15, 22, 23);
            System.out.println("指定时间:" + sendLocalDateTime);
            // 修改指定年月日时间
            sendLocalDateTime = sendLocalDateTime.withYear(2023);
            sendLocalDateTime = sendLocalDateTime.withDayOfMonth(10);
            System.out.println("修改时间可以任意:" + sendLocalDateTime);
    
            // 获取年月日时分秒具体值
            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());
            System.out.println(localDateTime.getSecond());
    
            // 转换年月日 和 时分秒,一般使用LocalDateTime转换就够了
            System.out.println(localDateTime.toLocalDate());
            System.out.println(localDateTime.toLocalTime());
    
            // LocalDateTime --》 String
            DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss E");
            String strTime = localDateTime.format(pattern);
            System.out.println("LocalDateTime --》 String:" + strTime);
    
            // String --》 LocalDateTime
            LocalDateTime localDateTime1 = LocalDateTime.parse(strTime, pattern);
            System.out.println("String --》 LocalDateTime:" + localDateTime1);
    
            // 让2022-01-15 22:30:36 的时间+1天,也可以加其它
            String strTime1 = "2022-01-15 22:30:36";
            DateTimeFormatter pattern1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime localDateTime3 = LocalDateTime.parse(strTime1, pattern1);
            localDateTime3 = localDateTime3.plusDays(1);
            String localDateTime3Str = localDateTime3.format(pattern1);
            System.out.println("让2022-01-15 22:30:36 的时间+1天:" + localDateTime3Str);
        }
    }

    六、Arrays 数组工具类

    1、常见的成员方法?

    • public static void sort(int[] a):排序
    • public static String toString(int[] a):将数组转换一个漂亮格式的字符串
    • public static int[] copyOf(int[] original,int newLength):复制数组,扩容
    package com.ppl.object;
    /*
    com.ppl.object:学习项目
    @user:广深-小龙
    @date:2022/1/15 19:05
    */
    
    import java.util.Arrays;
    
    public class Obj7_arrays {
        public static void main(String[] args) {
            // 将数组转为这种格式:[1, 23, 5]
            int[] arr = {4, 1, 68, 845, 54};
            String strArrays = Arrays.toString(arr);
            System.out.println(strArrays);
    
            // 复制arr及扩容
            arr = Arrays.copyOf(arr, 10);
            System.out.println(Arrays.toString(arr));
    
            new MyArr();
        }
    }
    
    class MyArr {
    
        public MyArr() {
            int[] arr = {1, 3, 2, 53, 0};
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
            }
            Arrays.sort(arr);
            System.out.println();
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
            }
        }
    }

    七、UUID及Random

    1、UUID:表示通用唯一标识符 (UUID) 的类。 UUID 表示一个 128 位的值。
    常见的成员方法?

    • public static UUID randomUUID():
    • public String toString():

    2、Random 随机数

    构造方法:public Random()

    成员方法:public int nextInt(int n)

    public class Obj8_UuidRandom {
        public static void main(String[] args) {
            // UUID 唯一标识不会重复
            String uuid = UUID.randomUUID().toString();
            System.out.println(uuid);
    
            // 随机数,1-100的整数
            Random r = new Random();
            int num = r.nextInt(100) + 1;   // (0-99) + 1
            System.out.println(num);
        }
    }

    欢迎来大家QQ交流群一起学习:482713805,博主微信+:gogsxl

  • 相关阅读:
    Linux学习
    官网地址
    Unsupported major.minor version 51.0
    获取select的option值
    网页中JS函数自动执行常用三种方法
    Python活力练习Day3
    时间复杂度的简单理解版本,非专业~~
    Python活力练习Day2
    Python活力练习Day1
    状压DP之LGTB 与序列
  • 原文地址:https://www.cnblogs.com/gsxl/p/15807948.html
Copyright © 2020-2023  润新知