常用类 | Java自学笔记

149 阅读9分钟

字符串相关的类

String类及其常用方法

String:字符串,使用一对""引起来表示
1.String声明为final的,不可被继承
2.String实现了Serializable接口:表示字符串是支持序列化的
        实现了Comparable接口:表示String可以比较大小
3.String内部定义了final char[] value用于存储字符串数据
4.String:代表不可变的字符序列。简称:不可变性
    体现:1.当对字符串重新赋值时,需要重写指定内存区域赋值,不能使用原有的value进行赋值
					2.当对现有的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值
					3.当调用String的replace方法修改指定字符或字符串时,也需要重新指定内存区域
5.通过字面量的方式(区别于new)给一个字符串赋值,此时的字符串值声明在字符串常量池中
6.字符串常量池中不会存储相同内容的字符串
  • String对象的创建

    • String str = “Hello”;
    • String s1 = new String(); //本质上this.value = new char[0];
    • String s2 = new String(String original); //this.value = original.value;
    • String s3 = new String(char[] a); //this.value = Arrays.copyOf(value, value.lenth);
    • String s4 = new String(char[] a, int startIndex, int count);
  • 字符串的特性

    • 常量与常量的拼接结果在常量池,且常量池中不会存在相同内容的常量
    • 只要其中有一个是变量,结果就在堆中
    • 如果拼接的结果调用intern()方法,返回值就在常量池中
    String s1 = "javaEE";
    String s2 = "hadoop";
    
    String s3 = "javaEEhadoop";
    String s4 = "javaEE" + "hadoop";
    String s5 = s1 + "hadoop";
    String s6 = "javaEE" + s2;
    String s7 = s1 + s2;
    
    System.out.println(s3 == s4);//true
    System.out.println(s3 == s5);//false
    System.out.println(s3 == s6);//false
    System.out.println(s3 == s7);//false
    System.out.println(s5 == s6);//false
    System.out.println(s5 == s7);//false
    System.out.println(s6 == s7);//false
    
    String s8 = s6.intern();//返回值得到的s8使用的常量池中已存在的“javaEEhadoop”
    System.out.println(s3 == s8);//true
    
  • String与基本数据类型、包装类之间的转换

    • String ——>基本数据类型、包装类:调用包装类的静态方法:parseXxx(str)
    • 基本数据类型、包装类 ——>String:调用String重载的valueOf(xxx)
  • String与char[]之间的转换

    • String ——>char[]:调用String的toCharArray方法

    • char[] ——> String:调用String的构造器

      public void test2(){
              String str1 = "abc123";
              char[] charArray = str1.toCharArray();
              for (int i = 0; i < charArray.length; i++) {
                  System.out.println(charArray[i]);
              }
      
      				char[] arr = {'h','e','l','l','o'};
              String str2 = new String(arr);
              System.out.println(str2);
          }
      
  • String与byte[]之间的转换

    • 编码:String ——>byte[]:调用String的getBytes[]
    • 解码:byte[] ——>String:调用String的构造器
    public void test3() throws UnsupportedEncodingException {
    
            String str1 = "abc123中国";
            byte[] bytes = str1.getBytes();//使用默认的字符集进行转换
            System.out.println(Arrays.toString(bytes));//遍历byte[]
    
            byte[] gbks = str1.getBytes("gbk");//使用gbk字符集编码
            System.out.println(Arrays.toString(gbks));
    
            System.out.println("***************************");
    
            String str2 = new String(bytes);
            System.out.println(str2);
    
            String str3 = new String(gbks);
            System.out.println(str3);//出现乱码,编码集和解码集不一致
    
            String str4 = new String(gbks, "gbk");
            System.out.println(str4);
    
        }
    
  • JVM中字符串常量池存放位置说明

    • JDK1.6:字符串常量池存储在方法区(永久区)
    • JDK1.7:字符串常量池存储在堆空间
    • JDK1.8:字符串常量池存储在方法区(元空间)

StringBuffer、StringBuilder

  • String、StringBuffer、StringBuilder三者异同

    • String:不可变的字符序列,底层使用char[]存储
    • StringBuffer:可变的字符序列,线程安全,效率低,底层使用char[]存储
    • StringBuilder:可变的字符序列,JDK5.0新增,线程不安全,效率高,底层使用char[]存储
    • 效率从高到低:StringBuilder > StringBuffer > String
  • 源码分析

    String str = new String();//char[] value = new char[0];
    String str1 = new String("abc");//char[] value = new char[]{'a','b','c'};
    
    StringBuffer sb1 = new StringBuffer();//char[] value = new char[16];底层创建一个长度为16的数组
    sb1.append('a');//value[0] = 'a';
    sb1.append('b');//value[1] = 'b';
    
    StirngBuffer sb2 = new StringBuffer("abc");//char[] value = new char["abc".length() + 16];
    //问题1. System.out.println(sb2.length());//3
    //问题2. 扩容问题:如果要添加的数据底层数组盛不下,就需要扩容底层数组
    				默认情况下,扩容为原来容量的2+2,同时将原有数组中的元素复制到新的数组中
    //开发中建议使用StringBuffer(int capacity)或StringBuilder(int capacity)
    
  • StringBuffer中的常用方法

    • 增:StringBuffer append(xxx):提供了很多append()方法,用于进行字符串拼接
    • 删:StringBuffer delete(int start, int end):删除指定位置的内容
    • 改:StringBuffer replace(int start, int end, String str):把[start, end)位置替换为str
    • 插:StringBuffer insert(int offset, xxx):在指定位置插入xxx
    • StringBuffer reverse():把当前字符序列逆转
    • public int indexOf(String str)
    • public String substring(int start, int end)
    • public int length()
    • 查:public char charAt(int n)
    • 改:public void setCharAt(int n, char ch)
  • String与StringBuffer、StringBuilder之间的转换

    • String —>StringBuffer、StringBuilder:调用StringBuffer、StringBuilder构造器
    • StringBuffer、StringBuilder —>String:调用String构造器;调用StringBuffer、StringBuilder的toString()

JDK8之前的日期时间API

System静态方法

System类提供的public static long currentTimeMillis()用来返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差

  • 计算世界时间的主要标准有

    • UTC (Coordinated Universal Time)
    • GMT (Greenwich Mean Time)
    • CST (Central Standard Time)

Date类

java.util.Date类

|——java.sql.Date类

  • 两个构造器的使用

    • 构造器一:Date():创建一个对应当前时间的Date对象
    • 构造器二:创建指定毫秒数的Date对象
  • 两个方法的使用

    • toString():显示当前的年月日时分秒
    • getTime():获取当前Date对线对应的毫秒数(时间戳)
  • java.sql.Date对应着数据库中的日期类型的变量

    • 如何实例化
    • 如何将java.util.Date对象转换为java.sql.Date对象
public void test2(){
        //构造器一:Date():创建一个对应当前时间的Date对象
        Date date1 = new Date();
        System.out.println(date1.toString());//显示当前年月日时分秒
        System.out.println(date1.getTime());//获取当前Date对象对应的毫秒数(时间戳)

        //构造器二:
        Date date2 = new Date(1550306204104L);
        System.out.println(date2.toString());

        //创建java.sql.Date对象
        java.sql.Date date3 = new java.sql.Date(352342353424L);
        System.out.println(date3.toString());//显示年月日

        //如何将java.util.Date对象转换为java.sql.Date对象
        Date date6 = new Date();
        java.sql.Date date7 = new java.sql.Date(date6.getTime());
    }

Calender类

public void testCalendar(){
        //1.实例化
        //方式一:创建其子类(GregorianCalendar)的构造器
        //方式二:调用其静态方法
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.getClass()); //class java.util.GregorianCalendar

        //2.常用方法
        //get()
        int days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);
        System.out.println(calendar.get(Calendar.DAY_OF_WEEK));

        //set()
        calendar.set(Calendar.DAY_OF_MONTH, 22);
        days = calendar.get(Calendar.DAY_OF_MONTH);//修改本身的值
        System.out.println(days);

        //add()
        calendar.add(Calendar.DAY_OF_MONTH, 3);
        days = calendar.get(Calendar.DAY_OF_MONTH);//修改本身的值
        System.out.println(days);

        //getTime():日历类 ---> Date
        Date date = calendar.getTime();
        System.out.println(date);

        //setTime(): Date ---> 日历类
        Date date1 = new Date();
        calendar.setTime(date1);
        days = calendar.get(Calendar.DAY_OF_MONTH);//修改本身的值
        System.out.println(days);
    }

//获取月份时,一月是0,二月是1……
//获取星期时:周日是1,周一是2……

SimpleDateFormat类

  • 两个操作

    • 格式化:日期 ——> 字符串
    • 解析:格式化的逆过程,字符串 ——> 日期
public void testSimpleDateFormat() throws ParseException {
        //实例化SimpleDateFormat:使用默认构造器
        SimpleDateFormat sdf = new SimpleDateFormat();

        //格式化:日期 ---> 字符串
        Date date = new Date();
        System.out.println(date);

        String format = sdf.format(date);
        System.out.println(format);

        //解析:格式化逆过程,字符串 ---> 日期
        String str = "22-5-14 下午5:57";
        Date date1 = sdf.parse(str);
        System.out.println(date1);

        //---------------------按照指定方式格式化:调用带参构造器-----------------------
        //SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //格式化
        String format1 = sdf1.format(date);
        System.out.println(format1);
        //解析
        Date date2 = sdf1.parse("2022-05-14 06:15:56");
    }

JDK8中新日期时间API

LocalDate、LocalTime、LocalDateTime

public void test1(){
        //now()获取当前日期、时间、日期+时间
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();

        System.out.println(localDate);
        System.out.println(localTime);
        System.out.println(localDateTime);

        //of():设置指定的年月日时分秒,无偏移量
        LocalDateTime localDateTime1 = localDateTime.of(2020, 10, 20, 10, 30, 21);
        System.out.println(localDateTime1);

        //getXxx()
        System.out.println(localDateTime.getDayOfMonth());
        System.out.println(localDateTime.getDayOfWeek());
        System.out.println(localDateTime.getDayOfYear());
        System.out.println(localDateTime.getMonth());
        System.out.println(localDateTime.getMinute());
        System.out.println(localDateTime.getMonthValue());

        //体现不可变性
        //withXxx():设置相关属性
        LocalDate localDate1 = localDate.withDayOfMonth(22);
        System.out.println(localDate);
        System.out.println(localDate1);

        //不可变性
        LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
        System.out.println(localDateTime);
        System.out.println(localDateTime3);
    }

Instant

  • 类似于java.util.Date类
public void test2(){
        Instant instant = Instant.now();//格林威治时间
        System.out.println(instant);

        //添加时间偏移量
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);

        //获取对应的毫秒数自1970.1.1.0.0.0
        long milli = instant.toEpochMilli();
        System.out.println(milli);

        //通过给定的时间获取Instant实例
        Instant instant1 = Instant.ofEpochMilli(3243543225342L);
        System.out.println(instant1);
    }

DateTimeFormatter

  • 格式化或解析日期、时间,类似于SimpleDateFormat
		public void test3(){
        //方式一:预定义标准格式
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //格式化:日期 ---> 字符串
        LocalDateTime localDateTime = LocalDateTime.now();
        String str1 = formatter.format(localDateTime);
        System.out.println(localDateTime);
        System.out.println(str1);

        //解析:字符串 ---> 日期
        TemporalAccessor parse = formatter.parse("2022-05-14T20:42:22.121");
        System.out.println(parse);

        //方式二:本地化相关的格式。如:ofLocalizedDate()
        //FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        //格式化
        String str2 = formatter1.format(localDateTime);
        System.out.println(str2);

        //本地化相关格式,如:ofLocalizedDate()
        //FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        String str3 = formatter2.format(localDateTime.now());
        System.out.println(str3); //2022年5月14日 星期六

        //方式三:自定义格式。如:ofPattern("yyyy-MM-dd hh:mm:ss")
        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //格式化
        String str4 = formatter3.format(localDateTime.now());
        System.out.println(str4);

        //解析
        TemporalAccessor accessor = formatter3.parse("2022-05-14 08:56:17");
        System.out.println(accessor);
    }

其他类

  • ZoneId:包含了所有时区信息
  • ZonedDateTime
  • Clock
  • TemporalAdjuster
  • TemporalAdjusters

Java比较器

  • 在Java中经常会涉及到对象数组的排序问题,那么就涉及到对象之间的比较问题

  • Java实现对象排序的方式有两种

    • 自然排序:java.lang.Comparable
    • 定制排序:java.util.Comparator

Comparable接口

  • Comparable接口的使用举例

    • 像String、包装类等实现了Comparable接口,重写了compareTo(obj)方法,给出了比较两个对象大小的方式

    • 像String、包装类重写compareTo()方法以后,进行了从小到大排列

    • 重写compareTo(obj)的规则

      • 如果当前对象this大于形参对象obj,则返回正整数
      • 如果当前对象this小于形参对象obj,则返回负整数
      • 如果当前对象this等于形参对象obj,则返回零
    • 对于自定义类如果需要排序,可以让自定义类实现Comparable接口,重写compareTo(obj)方法,在compareTo(obj)方法中指明如何排序

public void test2(){

    Goods[] arr = new Goods[4];
    arr[0] = new Goods("lenovoMouse", 34);
    arr[1] = new Goods("dellMouse", 45);
    arr[2] = new Goods("xiaomiMouse", 54);
    arr[3] = new Goods("huaweiMouse", 23);

    Arrays.sort(arr);

    System.out.println(Arrays.toString(arr));

}

public class Goods implements Comparable{

    private String name;
    private double price;

    public Goods(){

    }

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

    public String getName(){
        return name;
    }

    //指明商品比较大小的方式
    @Override
    public int compareTo(Object o) {
        if (o instanceof Goods){
            Goods goods = (Goods)o;
            if(this.price > goods.price){
                return 1;
            }else if(this.price < goods.price){
                return -1;
            }else{
                return 0;
            }
            //方式二
            //return Double.compare(this.price, goods.price);
        }
        throw new RuntimeException("传入的数据类型不一致!");
    }

    @Override
    public String toString() {
        return "Goods{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

Comparator接口

  • 当元素的类型没有实现java.lang.Comparable接口而又不方便修改代码,或者实现了java.lang.Comparable接口的排序规则不适合当前的操作,可以考虑使用Comparator的对象来排序

  • 重写compare(Object o1, Object o2)方法,比较o1和o2的大小

    • 如果方法返回正整数,则表示o1大于o2
    • 如果返回0,表示相等
    • 返回负整数,表示o1小于o2
		@Test
    public void test3(){
        String[] arr = new String[]{"AA","CC","KK","MM","GG","JJ","DD"};
        Arrays.sort(arr, new Comparator() {
            //按照字符串从大到小的顺序排列
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof String && o2 instanceof String){
                    String s1 = (String) o1;
                    String s2 = (String) o2;
                    return -s1.compareTo(s2);
                }
                throw new RuntimeException("输入的数据类型不一致");
            }
        });
        System.out.println(Arrays.toString(arr));
    }
    
    @Test
    public void test4(){
        Goods[] arr = new Goods[4];
        arr[0] = new Goods("lenovoMouse", 34);
        arr[1] = new Goods("dellMouse", 45);
        arr[2] = new Goods("xiaomiMouse", 54);
        arr[3] = new Goods("huaweiMouse", 23);

        Arrays.sort(arr, new Comparator() {
            //按照产品名称从低到高,再按照价格从高到低排序
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Goods && o2 instanceof Goods){
                    Goods g1 = (Goods)o1;
                    Goods g2 = (Goods)o2;
                    if (g1.getName().equals(g2.getName())){
                        return -Double.compare(g1.getPrice(), g2.getPrice());
                    }else{
                        return g1.getName().compareTo(g2.getName());
                    }
                }

                throw new RuntimeException("输入的数据类型不一致");
            }
        });

        System.out.println(Arrays.toString(arr));
    }
  • 两种排序方法对比

    • Comparable接口的方式一旦确定,保证Comparable接口实现类的对象在任何位置都可以比较大小
    • Comparator接口属于临时性的比较

System类

Math类

BigInteger与BigDecimal