Java常用类

一、字符串

1、String类

  • String是一个final类,代表不可变字符序列
  • 字符串是常量,它们的值创建后不可更改。
  • 创建字符串一般使用String str1 = “abc”; 或者 String str2 = new String(“abc”);来创建字符对象。
    • 两者区别:

String类常用方法

  1. int length():返回字符串长度
  2. char charAt(int index):返回索引处的字符
  3. boolean isEmpty():判断是否为空字符串
  4. String toLowerCase():将String里的所有字符转换成小写
  5. String toUpperCase():将String里的所有字符转换成大写
  6. String trim():返回字符串副本,忽略开头空白和尾部空白
  7. boolean equals(Object obj):比较字符串是否相同
  8. boolean equalsIgnoreCase(String anotherString):忽略大小写比较字符串是否相同
  9. String concat(String str):将指定字符串拼接到此字符串尾部,等价于“+”
  10. int compareTo(String anotherStr):比较两个字符串大小
  11. String subString(int beginIndex, int endIndex):返回新字符串,它是此字符串从beginIndex截取到endIndex(不包含)的子字符串。其中若endIndex省略,则默认截取到最后
  12. boolean endsWith(String suffix):判断是否以指定的后缀结尾
  13. boolean startsWith(String prefix):判断是否以指定的前缀开始
  14. boolean startsWith(String prefix, int toffset):判断从指定的索引开始的子字符串,是否以指定的前缀开始
  15. boolean contains(CharSequences s):当且仅当此字符串包含指定的char值序列,返回true
  16. int indexOf(String str):返回指定子字符串第一次出现的索引
  17. int indexOf(String str, int fromIndex):返回指定子字符串第一次出现的索引,从指定的索引开始
  18. int lastIndexOf(String str):返回指定子字符串最右边出现的索引
  19. int lastIndexOf(String str, int fromIndex):返回指定子字符串最右边出现的索引,从指定的索引开始反向搜索
  20. boolean matches(String regex):判断字符串是否匹配某个正则表达式

String和其他类型的转换

  • String转int:Integer.parseInt(String s)
  • int转String:String.valueOf(int i)
  • String转char[]:char[] toCharArray()
  • char[]转String:new String(char[] value)
  • String转byte[]:byte[] getBytes()
  • byte[]转String:new String(byte[] bytes)

2、StringBuffer和StringBuilder类

  • String、StringBuffer、StringBuilder三者区别:
    • String不可变的字符序列
    • StringBuffer可变的字符序列;线程安全,效率低
    • StringBuilder可变的字符序列;线程不安全,效率高
    • 效率:StringBuilder > StringBuffer > String
  • 三者创建字符串底层区别:
    • String str1 = new String();====>char[] value = new char[0];
    • String str2 = new String("abc");====>char[] value = new char[]{'a','b','c'};
    • StringBuffer sb1 = new StringBuffer();====>char[] value = new Char[16];相当于底层创建了长度为16的char数组
    • sb1.append('a');====>value[0] = 'a';
    • sb1.append('b');====>value[1] = 'b';
    • StringBuffer sb2 = new StringBuffer("abc");====>char[] value = new Char["abc".length() + 16];
    • 扩容问题:如果append的数据底层放不下,就需要扩容,默认情况下,扩容的容量为原来的容量两倍+2,同时将原来的数组元素复制到扩容后的数组中。
  • StringBuffer\StringBuilder类常用且特有方法
    • StringBuffer append(xxx):在当前字符串后拼接
    • 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():把当前字符串序列逆转
    • 注:如上方法支持链式操作

二、日期及时间

1、System类获取时间戳

  • System.currentTimeMillis():返回当前时间和1970年1月1日0时0分0秒之间的以毫秒为单位的时间差

    1
    2
    3
    4
    5
    @Test
    public void test1(){
    long time = System.currentTimeMillis();
    System.out.println(time); //1646468583764
    }

2、Data类

  • 使用Data()空参构造器:获取当前时间

    1
    2
    3
    4
    5
    6
    7
    @Test
    public void test2(){
    Date date = new Date(); //注意:导入的包为java.util.Date
    System.out.println(date); //这里相当于调用了date.toString(),结果:Sat Mar 05 16:28:35 CST 2022

    System.out.println(date.getTime()); //getTime():获取当前Date对象的时间戳
    }
  • 使用Data(long date)构造器:获取指定毫秒数对应时间

    1
    2
    3
    4
    5
    @Test
    public void test3(){
    Date date = new Date(1346400000000L);
    System.out.println(date); //Fri Aug 31 16:00:00 CST 2012
    }

3、SimpleDateFormate类

  • SimpleDateFormate:对日期进行格式化或逆格式化

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    //使用SimpleDateFormat()空参构造器
    @Test
    public void test1(){
    Date date = new Date(); //当前时间
    SimpleDateFormat format = new SimpleDateFormat();
    String t1 = format.format(date);//格式化时间
    System.out.println(t1); //2022/3/5 下午4:46

    String str = "2022/2/2 下午2:22"; //必须满足默认格式!!
    try {
    Date d1 = format.parse(str); //逆格式化
    System.out.println(d1); //Wed Feb 02 14:22:00 CST 2022
    } catch (ParseException e) {
    e.printStackTrace();
    }
    }

    //使用SimpleDateFormat(String pattern)有参构造器
    @Test
    public void test2(){
    Date date = new Date(); //当前时间
    //指定格式化的日期时间格式:yyyy-MM-dd hh:mm:ss
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String s2 = format1.format(date);
    System.out.println(s2); //2022-03-05 16:55:15

    String str = "2022-2-2 14:22:00"; //必须满足:yyyy-MM-dd HH:mm:ss格式!!
    try {
    Date d1 = format1.parse(str); //逆格式化
    System.out.println(d1); //Wed Feb 02 14:22:00 CST 2022
    } catch (ParseException e) {
    e.printStackTrace();
    }
    }

4、Calendar类

  • Calendar类是一个抽象类,用于完成日期字段间相互操作的功能

  • 获取Calendar实例方法:

    • 使用Calendar.getInstance()方法。
    • 调用其子类GregorianCalendar的构造器(不常用)。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    @Test
    public void test1() {
    Calendar calendar = Calendar.getInstance();
    //get():获取一些日历信息
    System.out.println(calendar.get(Calendar.DAY_OF_YEAR));//DAY_OF_YEAR:今年第几天,结果:64
    //set():设置日历信息
    calendar.set(Calendar.DAY_OF_MONTH, 10);//DAY_OF_MONTH:这个月第几天,设置为这个月第十天
    int d1 = calendar.get(Calendar.DAY_OF_MONTH);
    System.out.println(d1); //10
    //add():增加或减少天数
    calendar.add(Calendar.DAY_OF_MONTH,-3);//在这个月第十天基础上减少三天
    int d2 = calendar.get(Calendar.DAY_OF_MONTH);
    System.out.println(d2);//7
    //getTime():日历类转成Date
    Date time = calendar.getTime();
    System.out.println(time);//Mon Mar 07 17:19:47 CST 2022
    //setTime():Date转成日历类
    Date date = new Date();
    calendar.setTime(date);
    System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//5
    }
  • 注意Calendar会有偏移量:

    • 获取月份时:一月是0,二月是1,十二月时11
    • 获取星期时:周日为1,周一为2,周六是7

5、JDK8的日期时间类

5.1、LacalDate、LocalTime、LocalDateTime

  • 类似于Calendar

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    @Test
    public void test1() {
    //now()获取当前日期时间
    LocalDate localDate = LocalDate.now();
    LocalTime localTime = LocalTime.now();
    LocalDateTime localDateTime = LocalDateTime.now();

    System.out.println(localDate); //2022-03-05
    System.out.println(localTime); //22:21:07.430041400
    System.out.println(localDateTime); //2022-03-05T22:21:07.430041400

    //of()指定年月日时分秒,区别于Calendar,LocalDateTime没有偏移量
    LocalDateTime dateTime = LocalDateTime.of(2021, 2, 20, 13, 55, 11);
    System.out.println(dateTime); //2021-02-20T13:55:11

    //getXxx()获取一些时间日期的信息
    System.out.println(localDateTime.getDayOfMonth()); //5,获取当前月第几天
    System.out.println(localDateTime.getDayOfWeek());//SATURDAY,获取周几
    System.out.println(localDateTime.getMonth()); //MARCH,获取月份
    System.out.println(localDateTime.getMonthValue()); //3,月份
    System.out.println(localDateTime.getMinute()); //28,获取当前分钟

    //withXxx()设置日期时间信息,有返回值,体现了不可变性,而Calendar是可变的
    LocalDateTime localDateTime1 = localDateTime.withDayOfMonth(20); //修改当前是这个月第20天
    System.out.println(localDateTime); //原来:2022-03-05T22:36:44.131587900
    System.out.println(localDateTime1);//现在:2022-03-20T22:36:44.131587900
    LocalDateTime localDateTime2 = localDateTime.withHour(10); //设置当前时间为10点
    System.out.println(localDateTime); //原来:2022-03-05T22:36:44.131587900
    System.out.println(localDateTime2);//现在:2022-03-05T10:36:44.131587900

    //plusXxx()在当前时间基础上增加
    LocalDateTime localDateTime2 = localDateTime.plusYears(10);//当前时间上加十年
    System.out.println(localDateTime);//原来:2022-03-05T22:41:34.492610800
    System.out.println(localDateTime2);//现在:2032-03-05T22:41:34.492610800

    //minusXxx()在当前时间基础上减去
    LocalDateTime localDateTime1 = localDateTime.minusMonths(5);//当前时间上减去五个月
    System.out.println(localDateTime); //原来:2022-03-05T22:44:12.741669700
    System.out.println(localDateTime1);//现在:2021-10-05T22:44:12.741669700
    }

5.2、瞬时:Instant类

  • 类似于Date类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    @Test
    public void test1() {
    //now()获取的是格林尼治标准时间,和北京时间差8小时
    Instant instant = Instant.now();
    System.out.println(instant); //2022-03-05T14:57:58.688334800Z

    //atOffset()设置时区偏移量
    OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
    System.out.println(offsetDateTime);//2022-03-05T22:57:58.688334800+08:00

    //获取从1970-1-1 0:0:0到现在毫秒数,类似Date的getTime()
    long milli = instant.toEpochMilli();
    System.out.println(milli); //1646492278688

    //ofEpochMilli()根据毫秒数创建对应的Instant时间,类似Date(long millis)
    Instant instant1 = Instant.ofEpochMilli(1046492191329L);
    System.out.println(instant1); //2003-03-01T04:16:31.329Z
    }

5.3、DateTimeFormatter类

  • 类似于SimpleDateFormat类,格式化时间日期

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @Test
    public void test1() {
    LocalDateTime localDateTime = LocalDateTime.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    //格式化
    String time = formatter.format(localDateTime);
    System.out.println(time); //2022-03-05 23:20:03

    //解析(反格式化)
    TemporalAccessor parse = formatter.parse("2002-12-08 20:18:21");
    System.out.println(parse); //{},ISO resolved to 2002-12-08T20:18:21
    }

三、Java比较器

1、Comparable接口

  • 例如对String数组进行排序:

    1
    2
    3
    4
    5
    6
    7
    @Test
    public void test1() {
    String[] arr = new String[]{"SS","MM","JJ","BB","KK","RR","OO"};
    Arrays.sort(arr);
    System.out.println(Arrays.toString(arr));
    //输出:[BB, JJ, KK, MM, OO, RR, SS]
    }
  • 这里可以自动按照英文字母顺序进行排序,是因为String类实现了Comparable接口,并且重写了CompareTo()方法,因此可以实现排序

1.1、自定义类实现Comparable自然排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* 商品类
*/
//1.实现Comparable接口
public class Goods implements Comparable<Goods> {

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;
}

public void setName(String name) {
this.name = name;
}

public double getPrice() {
return price;
}

public void setPrice(double price) {
this.price = price;
}

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

//2.实现Comparable接口的CompareTo()方法
@Override
public int compareTo(Goods o) {
if (this.price > o.price) {
return 1;
} else if (this.price < o.price) {
return -1;
} else {
return this.name.compareTo(o.name);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
public void test1() {
Goods[] goods = new Goods[5];
goods[0] = new Goods("苹果",5.1);
goods[1] = new Goods("西瓜",2.5);
goods[2] = new Goods("葡萄",3.3);
goods[3] = new Goods("橘子",2.9);
goods[4] = new Goods("橙子",2.5);

Arrays.sort(goods);
System.out.println(Arrays.toString(goods));
}
/* 结果:
[Goods{name='橙子', price=2.5},
Goods{name='西瓜', price=2.5},
Goods{name='橘子', price=2.9},
Goods{name='葡萄', price=3.3},
Goods{name='苹果', price=5.1}] */

2、Comparator接口

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

  • 例如:还是对String数组进行排序,如果仅仅使用String里面自带的CompareTo()方法,那么只能从小到大进行排序,而不能进行从大到小排序,且我们无法修改String源码,因此这时就需要用到Comparator接口进行自定义排序

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    @Test
    public void test2() {
    String[] arr = new String[]{"SS","MM","JJ","BB","KK","RR","OO"};
    //这里使用了实现Comparator接口的匿名对象
    Arrays.sort(arr, new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
    //只需要加个负号就能逆向排序
    return -o1.compareTo(o2);
    }
    });
    System.out.println(Arrays.toString(arr));
    //结果:[SS, RR, OO, MM, KK, JJ, BB]
    }

四、System类

  • 该类构造器时私有的,因此无法进行实例化,其内部成员变量和方法都是static的,因此可以很方便的调用。
  • 常用方法:
    • native long currentTimeMillis():返回当前计算机时间和GMT时间1970-1-1 0:0:0所差的毫秒数。
    • void exit(int status):用于退出程序,其中status为0代表正常退出,非0代表异常退出。使用该方法可以在图形界面编程中实现程序退出功能。
    • void gc():该方法作用是请求系统进行垃圾回收。至于系统是否立刻回收,取决于系统垃圾回收算法的实现以及系统执行情况。
    • String getProperty(String key):该方法用于获取系统属性名为key的属性对应值。常见的属性名说明如下:
      • java.version:java运行环境版本
      • java.home:java安装目录
      • os.name:操作系统名称
      • os.version:操作系统版本
      • user.name:用户的账户名
      • user.home:用户主目录
      • user.dir:用户当前工作目录

五、Math类

  • 其提供了一系列静态方法,用于数学计算。
    • abs:绝对值
    • acos,asin,atan,cos,sin,tan:三角函数
    • sqrt:平方根
    • pow(double a, double b):a的b次幂
    • log:自然对数
    • exp:e为底的指数
    • max(double a, double b), min(double a, double b):比较ab大小
    • random():返回0.0到0.1的随机数
    • long round(double a):double类型的a转long类型(四舍五入)
    • toDegress(double angrad):弧度转角度
    • toRadians(double angdeg):角度转弧度