08-Java常用类
字符串
String类
- 是一个final类,不可继承
- 实现了Serializable接口:表示字符串是支持序列化的。
- 实现了Comparable接口:表示String可比较大小
- String内部定义了final char[] value 用于存储字符串数据
- 代表不可变的字符序列
public class Str{
public static void main(String[] args){
String s1 = "abc";
String s2 = "abc"; //通过字面量的方式对字符串进行赋值,赋的值存储在常量值中,但s1,s2都是变量
System.out.println(s1 == s2); //true
//创建
String s3 = "hello"; //存储在方法区的常量池中
String s4 = new String("abc"); //通过new创建的对象在堆空间中
String s5 = new String(new char[]{'a','b','c'});
String s6 = s3 + "world"; //只要右边有变量,就是在堆空间中创建"helloworld"
String s7 = "helloworld"; //常量池中的"helloworld"
System.out.println(s6 == s7); //false
String s8 = s6.intern(); //返回值a强制在常量池中,即s8为常量池中的"helloworld"
System.out.println(s6 == s8) //true
}
}
- 常用方法;
public class Test{
public static void main(String[] args){
String s1 = "HelloWorld";
//获取长度
System.out.println(s1.length());
//获取指定索引的字符
System.out.println(s1.charAt(2)); // l
//是否为空
System.out.println(s1.isEmpty()); //false
//全小写
System.out.println(s1.toLowerCase()); //s1没变,输出为helloworld
//全大写
System.out.println(s1.toUpperCase()); //s1没变,输出为HELLOWORLD
//返回副本,去掉前空白与后空白
System.out.println(" hello world ".trim()); //hello world
//比较内容是否相同
System.out.println(s1.equals("HelloWorld")); //true
//忽略大小写比较内容是否相同
System.out.println(s1.eaualsIgnoreCase("helloworld")); //true
//连接
System.out.println(s1.concat("!")); //s1没变,返回值为HelloWorld!
//比较
System.out.println(s1.compareTo("HelloWorle")); // 'd'比'e'小,返回负数
//取子串
System.out.println(s1.substring(2)); //lloWorld
System.out.println(s1.substring(2,5)); //llo 左闭右开
//是否以指定字符串结尾
System.out.println(s1.endWith("ld")); //true
//是否以指定字符串开始
System.out.println(s1.startWith("hel")); //false
System.out.println(s1.startWith("ell",1)); //true 从索引为1开始为此字符串
//是否包含字符串
System.out.println(s1.contains("ello")); //true
//返回字符串第一次出现的位置,不存在返回-1
System.out.println(s1.indexOf("llo")); //2
System.out.println(s1.indexOf("abc")); //-1
System.out.println(s1.indexOf("l",4)); //从索引为4开始找,输出8
//从后往前找(索引还是从前)
System.out.println(s1.lastIndexOf("l")); //8
System.out.println(s1.lastIndexOf("l",4)); //3
//替换
String s2 = "aaddaaddee";
System.out.println(s2.replace("ad","bc")); //abcdabcdee
//正则匹配
System.out.println(s2.replaceAll("[ad]","bc")); //bcbcbcbcbcbcbcbcee
System.out.println(s2.replaceFirst("[ad]","bc")); //bcaddaaddee
//匹配
System.out.println(s2.matches("[abcde]*")); //true
//切片
String s3 = "hello|world|java";
String[] strs = s3.split("\\|"); //以正则表达式匹配到的字符串分割,返回数组
for(int i = 0;i < strs.length;i++){
System.out.println(strs[i]); //hello world java
}
}
}
- 转换
public class Test{
public static void main(String[] args){
//String -> char[]
String s1 = "abc123";
char[] ch1 = s1.toCharArray();
//char[] -> String
String s2 = new String(ch1);
//与字节数组
//String -> byte[]
byte[] bytes = s1.getBytes(); //使用默认的编码集转换-可加入参数指定字符集
System.out.println(Arrays.toString(bytes)); //[97,98,99,49,50,51]
//byte[] -> String
String s3 = new String(bytes); //abc
}
}
StringBuffer
- 可变字符序列
- 线程安全的,但效率低
- 底层char[]存储
StringBuilder
- 可变字符序列
- 线程不安全,但效率高
- 底层char[]存储
public class Test{
StringBuffer s1 = new StringBuffer("abc");
//增
s1.append(1);
s1.append('1');
System.out.println(s1);
//删
s1.delete(2,3); //左闭右开,删[2,3) ab11
System.out.println(s1);
//替换
s1.replace(2,4,"hello"); //abhello
System.out.println(s1);
//插入
s1.insert(2,"cd"); //abcdhello
System.out.println(s1);
//反转
s1.reverse(); //ollehdcba
s1.reverse(); //abcdhello
System.out.println(s1);
//子串-不修改s1
String s2 = s1.substring(1);
System.out.println(s1); //abcdhello
System.out.println(s2); //bcdhello
//长度
System.out.println(s1.length()); //9
//改
s1.setCharAt(0,'A'); //Abcdhello
System.out.println(s1);
//查
System.out.println(s1.charAt(0)); //A
}
StringBuilder类方法与StringBuffer相同
JDK8之前的时间类
1. System类中的时间
public class Test{
public static void main(String[] args){
//返回当前时间与1970年1月1日0时0分0秒0毫秒之间以毫秒为单位的时间差
long time = System.currentTimeMillis(); //时间戳
}
}
2. util中的Date类及其java.sql.Date子类
public class Test{
public static void main(String[] args){
//构造器1
Date date1 = new Date();
System.out.println(date1.toString()); //格式化的时间 Wed Dec 09 19:53:27 GMT+08:00 2020
System.out.println(date1.getTime()); //时间戳-同system中的时间戳 1607514807966
//构造器2
Date date2 = new Date(1607514807966L); //创建指定毫秒数的对象
System.out.println(date2.toString()); //Wed Dec 09 19:53:27 GMT+08:00 2020
//java.sql.Date
java.sql.Date date3 = new java.sql.Date(1607514807966L); //创建java.sql.Date对象
System.out.println(date3); //2020- 12-09
}
}
3. SimpleDateFormat
public class Test{
public static void main(String[] args){
try {
//SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat();
//默认格式化
Date date4 = new Date();
System.out.println(date4); //Wed Dec 09 22:10:17 GMT+08:00 2020
System.out.println(sdf.format(date4)); //20-12-9 下午10:10
//解析
String str = "20-12-10 上午11:11";
Date datef = sdf.parse(str);
System.out.println(datef);//Thu Dec 10 11:11:00 GMT+08:00 2020
//自定义格式化
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(sdf1.format(datef));//2020-12-10 11:11:00
//解析
Date date5 = sdf1.parse("2020-12-12 11:48:27");
System.out.println(date5); //Sat Dec 12 11:48:27 GMT+08:00 2020
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Calendar
- 获取日期是:一月为0,依次向后
- 获取星期是:周日是1,周一是2,依次先后
public class Test{
public static void main(String[] args){
//Calendar
//方式一创建其子类(GregorianCalendar)
//方式二:调用其静态方法
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getClass()); //就是GregorianCalendar类
//常用方法
//get()-获取Calendar的属性
System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); //9(今天12月9号) Calendar.DAY_OF_MONTH只是一个索引
//set()-修改
calendar.set(Calendar.DAY_OF_MONTH,22); //将calendar的日修改为22
System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); //22
//add()-在现有的基础上向后追加(可为负数)
calendar.add(Calendar.DAY_OF_MONTH,3);
System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); //25
//getTime():Calendar->Date
Date time = calendar.getTime();
System.out.println(time);
//setTime():Date->Calendar
Date stime = new Date();
calendar.setTime(stime);
}
}
JDK8新增时间类
LocalDate、LocalTime、LocalDateTime
public class Test{
public static void main(String[] args){
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDate); //2020-12-09
System.out.println(localTime); //23:21:46.604
System.out.println(localDateTime); //2020-12-09T23:21:46.604
//of():设置指定的年、月、日、时、分、秒。
LocalDateTime localDateTime1 = LocalDateTime.of(2020,10,10,11,11);
System.out.println(localDateTime1); //2020-10-10T11:11
//getXxx-获取
System.out.println(localDateTime.getMonth()); //DECEMBER
System.out.println(localDateTime.getMonthValue()); //12
//体现不可变性-原对象不变,返回新的变了的对象
//withXxx()-设置
LocalDate localDate1 = localDate.withDayOfMonth(22);
System.out.println(localDate); //2020-12-09
System.out.println(localDate1); //2020-12-22
//plusXxx()
LocalDateTime localDateTime2 = localDateTime.plusDays(5);
System.out.println(localDateTime2); //2020-12-14T23:35:23.454
//minusXxx()
LocalDateTime localDateTime3 = localDateTime.minusMonths(2);
System.out.println(localDateTime3); //2020-10-09T23:35:23.454
}
}
Instant类
public class Test{
public static void main(String[] args){
//now()获取本初子午线对应的标准时间
Instant instant = Instant.now();
System.out.println(instant); //2020-12-09T15:42:09.994Z
//添加时间偏移量
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8)); //8时区
System.out.println(offsetDateTime); //2020-12-09T23:42:09.994+08:00
//获取从1970-1-1 0:0:0开始的毫秒数
System.out.println(instant.toEpochMilli()); //1607528789151
//设置毫秒数
Instant instant1 = Instant.ofEpochMilli(1607528789151L);
System.out.println(instant1); //2020-12-09T15:45:47.308Z
}
}
DateTimeFormatter:格式化与解析日期、时间
public class Test{
public static void main(String[] args){
//方式一
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
//日期->字符串
formatter.format(LocalDateTime.now());
//解析:字符串->日期
TemporalAccessor parse = formatter.parse("2020-10-09T23:51:47.794");
System.out.println(parse); //{},ISO resolved to 2020-10-09T23:51:47.794
//方式二
DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
//格式化
String str = formatter1.format(LocalDateTime.now());
System.out.println(str); //20-12-10 上午12:03
//ofLocalizedDate()
DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
String str1 = formatter2.format(LocalDate.now());
System.out.println(str1); //2020-12-10
//方式三:自定义
DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
System.out.println(formatter3.format(LocalDateTime.now()));//2020-12-10 12:03:22
}
}
Java比较器
- 自然排序:实现Comparable接口的compareTol()方法
public class CompareTest {
public static void main(String[] args) {
String[] arr = new String[]{"AA","CC","GG","FF"};
Arrays.sort(arr); //String,包装类等实现了Compareable接口,实现了compareTo()方法,所以支持排序
System.out.println(Arrays.toString(arr));
//Good按商品优先价格排序,其次按名称排序
Good[] goods = new Good[4];
goods[0] = new Good("cs",7);
goods[1] = new Good("ew",30);
goods[2] = new Good("rw",12);
goods[3] = new Good("GF",44);
//Good实现了Comparable接口中的compareTo()方法,可以比较
Arrays.sort(goods);
System.out.println(Arrays.toString(goods));//goods重写了toString()方法,输出可以看到内容
//[Good{name='cs',price=7}, Good{name='rw',price=12}, Good{name='ew',price=30}, Good{name='GF',price=44}]
}
}
class Good implements Comparable{
public String name;
public int price;
public Good(){}
public Good(String name,int price){
this.name = name;
this.price = price;
}
//Comparable接口实现
/*
重写compareTo方法的规则
1. 如果当前对象this大于形参obj,则返回正整数
2. 如果当前对象this小于形参obj,则返回负整数
3. 如果当前对象this等于形参obj,则返回0
* */
@Override
public int compareTo(Object o) {
if(o instanceof Good){
Good good = (Good)o;
if(this.price > good.price){
return 1;
}else if(this.price < good.price){
return -1;
}else{
return this.name.compareTo(good.name);
}
}
return 0;
}
@Override
public String toString() {
return "Good{"+
"name='"+name+"'"+
",price="+price+
"}";
}
}
- 定制排序:java.util.Comparator
public class Test{
public static void main(String[] args){
String[] arr = new String[]{"AA","CC","GG","FF"};
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);
}
return 0;
}
});
System.out.println(Arrays.toString(arr));
//[GG, FF, CC, AA]
}
}
Comparable接口实现类的对象在任何位置都可以比较大小
Comparator属于临时使用
System类
- exit(int status);status为0表示正常退出,非0表示异常退出
- gc():请求系统进行垃圾回收(只是请求,回不回收不一定)
- getProperty(String key):获得系统中属性名为key的属性值
- java.version:java版本
- java.home:java安装目录
- os.name:操作系统名称
- os.version:操作系统版本
- user.name:用户账户名称
- user.home:用户的主目录
- user.dir:用户的当前工作目录
Math类
- 静态方法
- abs、acos、sqrt、pow等
BigInteger与BigDecimal类
- BigInteger可以表示任意大小的数,且有一些方法
- BigDecimal精度高