Java 常用类
第十三章:常用类
八大wrapper(包装类)
八种基本数据类型相应的引用类型——包装类
boolean--Boolean char--Character byte--Byte short--Short int--Integer long--Long float--Float double--Double Number类的wrapper

Boolean类

Character类

自动装箱和拆箱⭐
编译器底层优化:实现自动装箱和拆箱
packagecom.lcz.commenclass.wrapper;/** * @author lcz * @version 1.0 */publicclassWrapper{publicstaticvoidmain(String[] args){//jdk 5 前的 手动装箱和手动拆箱//装箱:基本类型-->包装类型//拆箱:包装类型-->基本类型//1.1手动装箱int i =1;//第一种方式Integer integer1 =Integer.valueOf(i);//第二种方式Integer integer2 =newInteger(i);//1.2手动拆箱int j = integer1.intValue();//2.1自动装箱int m =10;Integer integer3 = m;//底层调用:Integer.valueOf(m),属于编译器的底层优化//2.2自动拆箱Integer integer4 =newInteger(99);int n = integer4;//底层调用:integer4.intValue(),属于编译器的底层优化}}wrapper常用方法⭐
- wrapper到String :wrapper.toString()
- String到wrapper :new Wrapper(String),利用 wrapper 的重载构造器
- MIN_VALUE : Integer.MIN_VALUE
- MAX_VALUE
- isDIGIT:Character.isDIGIT(char)
- isLetter
- isUpperCase
- isLowerCase
- isWhitespace
- toUpperCase
- toLowerCase
packagecom.lcz.commenclass.wrapper;/** * @author lcz * @version 1.0 * * 关于wrapper的常用方法 */publicclassCommenMethod{publicstaticvoidmain(String[] args){//将wrapper转换为Stringint i =100;//1.String str = i +"";//2.String str1 =Integer.toString(i);//3.String str2 =String.valueOf(i);System.out.println(i);System.out.println(str1);System.out.println(str2);//将String转换为wrapperString str3 ="1234";int j =Integer.parseInt(str3);int m =newInteger(str3);//利用Integer的重载构造器System.out.println(Integer.MAX_VALUE);System.out.println(Integer.MIN_VALUE);char c ='a';System.out.println(Character.isDigit(c));System.out.println(Character.isLetter(c));System.out.println(Character.isUpperCase(c));System.out.println(Character.isLowerCase(c));System.out.println(Character.toUpperCase(c));System.out.println(Character.toLowerCase(c));System.out.println(Character.isWhitespace(c));}}Integer类面试题
数字常量直接赋值给Integer类对象

数字常量直接赋值给 Integer 类对象: 主要看范围:-128到127就是直接赋值(基本数据类型) 若不是则new创建Integer对象(引用数据类型) 基本数据类型和引用数据类型比较

注:只要有基本数据类型,就会判断值是否相等,因为包装类会进行自动拆箱!!! String类
String类继承图

String对象两种创建方式⭐
两种创建方式
两种方式: 1.直接赋值:String s = "lcz" 2.调用构造器:String s1 = new String("lcz") 解读: 1.先从常量池查看是否有"lcz"数据空间,若有,直接指向;若无则重新创建,然后指向。s最终指向的是常量池的空间地址 2.先在堆中创建空间,里面维护了value属性,指向常量池的"lcz"空间。若无,则重新创建,若有,则通过value指向。s1最终指向的是堆中的空间地址 两种创建方式的内存布局图

字符串特性⭐
不可变

1):String类是一个final类,不可继承修改value值,所以代表不可变的字符序列 2):字符串是不可变的。一个字符串对象一旦被分配,其内容是不可变的:因为value属性是私有的final类型 常量池对象无引用指向不创建

String a = "hello" + "abc";//优化等价 String a = "helloabc" 分析:编译器底层优化,判断创建的常量池对象,是否有引用指向,无则不创建 常量相加在池中,变量相加在堆中

规则: String c1 = "ab" + "cd";常量相加,是在池中 String c1 = a + b;只要有变量相加,是在堆中 解读:(String c1 = a + b) 1.先创建一个 StringBuilder sb = StringBulider() 2.执行 sb.append("hello") 3.sb.append("abc") 4.String c = sb.toString() toString方法返回的是一个 new的 value值是 helloabc 的堆中String对象 所以 c 指向 堆中的对象(String) value[] -> 常量池中 "helloabc" 堆、栈、常量池的理解

考察: 堆中对象、栈的创建、常量池的引用 形参指向的改变对实参的指向无影响,但形参对实参指向的对象进行改变会对实参产生影响 String类常用方法
- equals
- equalsIgnoreCase
- length
- indexOf
- lastIndexOf
- substring //截取指定范围内的子串
- trim //去前后空格
- charAt //获取某索引处的字符
- toUpperCase
- toLowerCase
- concat //拼接字符串
- replace
- split //分割字符串
- compareTo //字符串的比较,根据minlenth可比则比,否则len1-len2
- toCharArray //转换成字符数组
- format //格式化字符串:%s、%d、%c、%.2f
packagecom.lcz.commenclass.string;/** * @author lcz * @version 1.0 */publicclassString01{publicstaticvoidmain(String[] args){String s1 ="hello";String s2 =" abc ";System.out.println(s1.equals(s2));System.out.println(s1.length());System.out.println(s1.concat(s2));System.out.println(s1.indexOf("e"));System.out.println(s1.lastIndexOf("l"));System.out.println(s1.substring(1,3));System.out.println(s1.substring(1));System.out.println(s2.trim());System.out.println(s2.charAt(0));System.out.println(s2.toLowerCase());System.out.println(s2.toLowerCase());System.out.println(s2.charAt(4));System.out.println(s1.compareTo(s2));System.out.println(s1.toCharArray());char[] char1 = s1.toCharArray();System.out.println(char1[0]);}}StringBuffer类
介绍⭐
StringBuffer代表可变的字符序列 因为 StringBuffer 字符内容 是存在 char[] value,所以在变化(增加/删除)时,不用每次都创建新对象,所以效率高于String 只有数组空间已满,扩容时需创建新对象,更换地址 Sring VS StringBuffer⭐
1.String保存的是 字符串常量,里面的值不能更改,每次String类的更新实际上就是更改地址,效率较低//private final char value[] 存放在常量池2.StringBuffer保存的是 字符串变量,里面的值可以更改,每次StringBuffer的更新实际上可以更新内容,不用每次都更新地址,效率较高//char[] value 存放在堆StringBuffer的构造器⭐
1.StringBuffer(): 初始容量为16个字符 2.StringBuffer(int capacity)://capacity[容量] 具有指定初始容量 3.StringBuffer(String str): str.length()+16String和StringBuffer相互转换
1.String——>StringBuffer:String s ="hello";(1):StringBuffer b1 =newStringBuffer(s);(2):StringBuffer b2 =newStringBuffer(); b2.append(s);2.StringBuffer——>String:(1):String s1 = b1.toString();(2):String s2 =newString(b1);StringBuffer常见方法
增append(str)
删delete(start,end)
改replace(start,end,str)
查indexOf(str)
插insert(index,str)
获取长度length
packagecom.lcz.commenclass.StringBuffer;/** * @author lcz * @version 1.0 * * 关于StringBuffer方法:增删改查插长度 */publicclassStringBuffer01{publicstaticvoidmain(String[] args){StringBuffer s =newStringBuffer("hello");//增 s.append(','); s.append("张三丰").append(100).append(true);System.out.println(s);//删 s.delete(3,5);System.out.println(s);//改 s.replace(3,5,"lcz");System.out.println(s);//查int indexOf = s.indexOf("lcz");System.out.println(indexOf);//插 s.insert(3,"lhc");System.out.println(s);//长度System.out.println(s.length());}}StringBuilder类⭐
和 StringBuffer 的区别: StringBuilder 存在线程安全问题 因为没有做互斥处理,没有用 Synchronized 关键字 所以单线程场景用 StringBuilder,多线程场景用 StringBuffer三个字符串类优缺点及选择⭐
- String:不可变字符序列,效率低,但是复用率高
- StringBuffer:可变字符序列、效率较高(增删)、线程安全
- StringBuilder:可变字符序列,效率最高、线程不安全
结论:
1.如果字符串存在大量的修改操作,一般使用StringBuffer或StringBuilder 2.如果字符串存在大量的修改操作,并在单线程的情况,使用 StringBuilder 3.如果字符串存在大量的修改操作,并在多线程的情况,使用 StringBuffer 4.如果字符串很少修改,被多个对象引用,使用String,比如配置信息等 三个字符串类效率测试
packagecom.lcz.commenclass.String_StringBuffer_StringBuilder;/** * @author lcz * @version 1.0 * * String、StringBuffer、StringBuilder效率测试 */publicclass test {publicstaticvoidmain(String[] args){String text ="";long startTime =0L;long endTime =0L;StringBuffer buffer =newStringBuffer("");StringBuilder builder =newStringBuilder("");//StringBuffer startTime =System.currentTimeMillis();for(int i =0;i <20000;i++){ buffer.append(String.valueOf(i));} endTime =System.currentTimeMillis();System.out.println("StringBuffer的执行时间为:"+(endTime - startTime));//StringBuilder startTime =System.currentTimeMillis();for(int i =0;i <20000;i++){ builder.append(String.valueOf(i));} endTime =System.currentTimeMillis();System.out.println("StringBuilder的执行时间为:"+(endTime - startTime));//String startTime =System.currentTimeMillis();for(int i =0;i <20000;i++){ text += i;} endTime =System.currentTimeMillis();System.out.println("String的执行时间为:"+(endTime - startTime));}}Math类常用方法
- abs
- pow:返回double
- ceil:返回double
- floor:返回double
- round:四舍五入,返回long
- sqrt:返回double
- randon:返回double
- max
- min
- 获取一个 a - b 之间的一个随机整数:(int)(a + Math.random()*(b-a+1))
packagecom.lcz.commenclass.math;/** * @author lcz * @version 1.0 * * 关于:Math类相关方法 */publicclassMath01{publicstaticvoidmain(String[] args){//1.absSystem.out.println(Math.abs(-9));//2.pow,返回doubleSystem.out.println(Math.pow(2,3));//3.ceil,返回doubleSystem.out.println(Math.ceil(3.5));//4.floor,返回doubleSystem.out.println(Math.floor(-4.3));//5.round,返回longlong round =Math.round(4.0001);System.out.println(round);//6.sqrt,返回doubledouble res =Math.sqrt(16);System.out.println(res);//7.random,返回[0,1)之间的小数,返回doubleint a =2,b =7;int num =(int)(a +Math.random()*(b-a+1));System.out.println(num);}}Arrays类常用方法
- toString(arr):返回数组的字符串形式
- sort(arr)、sort(arr,new Compartor{}):无返回值
- 自然排序和基于二叉树排序的定制排序
- 基于冒泡的定制排序
- binarySearch(arr,element):通过折半查找法进行查找,要求为有序数组,时间复杂度:O(以2为底n的对数)
- copyOf(arr,len):数组元素的复制,
- fill(arr,fillElem):填充数组元素
- equals(arr1,arr2):比较两个数组元素内容是否完全一致
- asList:将一组值,转换成List(集合)
packagecom.lcz.commenclass.arrays;importjava.util.Arrays;importjava.util.Comparator;importjava.util.List;/** * @author lcz * @version 1.0 * * 关于Arrays01类的相关方法 */publicclassArrays01{publicstaticvoidmain(String[] args){//1.toString(arr)System.out.println("===n1定制排序前===");Integer[] n1 ={1,2,3,8,4,9,5};System.out.println(Arrays.toString(n1));//2.sort(arr)、sort(arr,new Compartor{})//Arrays.sort(n1);//System.out.println("===自然排序后===");//System.out.println(Arrays.toString(n1));System.out.println("===n1定制排序后===");Arrays.sort(n1,newComparator(){//n1需要为对象数组,不能是基本类型数组@Overridepublicintcompare(Object o1,Object o2){int n1 =(Integer) o1;int n2 =(Integer) o2;return n2 - n1;}});System.out.println(Arrays.toString(n1));//3.基于冒泡的定制排序int[] n2 ={2,5,3,6,4,7,2};System.out.println("===n2定制排序前===");System.out.println(Arrays.toString(n2));bubbleSort(n2,newComparator(){@Overridepublicintcompare(Object o1,Object o2){int n1 =(Integer) o1;int n2 =(Integer) o2;return n2 - n1;}});System.out.println("===n2定制排序后");System.out.println(Arrays.toString(n2));//4.binarySearch//要求为有序数组,无序数组排为有序也不行,若找不到,返回-(low+1),low为若存在的索引值int[] n3 ={1,2,3,4};System.out.println(Arrays.binarySearch(n3,2));//5.copyOf(arr,len)//(1):len > arr.length:补0//(2):len < 0 抛出异常NegativeArraySizeException//(3):底层调用的是System.arraycopy()int[] arr2 =Arrays.copyOf(n3,3);System.out.println(Arrays.toString(arr2));//6.fill(arr,fillElem)Arrays.fill(n3,1);System.out.println(Arrays.toString(n3));//7.equals(arr1,arr2)System.out.println(Arrays.equals(n2,n3));//8.asList//(1):asList方法,将(2,3,45,5)转成一个集合//(2):编译类型:List(接口)//(3):运行类型:java.util.Arrays$ArrayList:是Arrays的静态内部类ArrayListList asList =Arrays.asList(2,3,45,5);System.out.println("asList:"+ asList);System.out.println("asList运行类型:"+ asList.getClass());}publicstaticvoidbubbleSort(int[] arr1,Comparator c){int temp =0;for(int i =0; i < arr1.length; i++){for(int j =0; j < arr1.length -i -1; j++){if(c.compare(arr1[j],arr1[j+1])>0){ temp = arr1[j]; arr1[j]= arr1[j+1]; arr1[j+1]= temp;}}}}}System类常用方法
- exit:退出当前程序
- arraycopy:复制数组元素,用于底层调用(Arrays.copyOf)
- currentTimeMillens:返回当前时间距离1970-1-1 0:0:0的毫秒数
- gc:运行垃圾回收机制 System.gc();
packagecom.lcz.commenclass.system;/** * @author lcz * @version 1.0 * * 关于System类相关方法 */publicclassSystem_{publicstaticvoidmain(String[] args){//1.exit//0:表示程序退出的状态:正常退出//System.exit(0);//2.arraycopy//参数://src:原数组//srcPos:原数组复制起始位置//dest:目标数组//destPos:目标数组复制起始位置//length:复制的元素长度int[] n1 ={1,2,3};int[] n2 =newint[3];System.arraycopy(n1,0,n2,0,1);for(int i =0; i < n2.length; i++){System.out.println(n2[i]);}//3.currentTimeMillens:格林尼治时间System.out.println(System.currentTimeMillis());//4.gcSystem.gc();}}BigInteger和BigDecimal
应用场景:
1):BigInteger适合保存比较大的整型
2):BigDecimal适合保存精度更高的浮点型(小数)
常用方法:
- add
- subtract
- multiply
- divide
packagecom.lcz.commenclass.bignum;importjava.math.BigDecimal;/** * @author lcz * @version 1.0 * * 关于BigDecimal类相关方法 */publicclassBigDecimal_{publicstaticvoidmain(String[] args){BigDecimal bigDecimal1 =newBigDecimal("161618.12222222222222222222");BigDecimal bigDecimal2 =newBigDecimal("161618.122222222222222");System.out.println(bigDecimal2.add(bigDecimal1));System.out.println(bigDecimal2.subtract(bigDecimal1));System.out.println(bigDecimal2.multiply(bigDecimal1));System.out.println(bigDecimal2.divide(bigDecimal1));//可能会报异常 Non-terminating decimal expansion//因为碰到除不尽,无限循环,精度又很大,就异常:不可终止的小数扩展}}packagecom.lcz.commenclass.bignum;importjava.math.BigInteger;/** * @author lcz * @version 1.0 * * BigInteger类相关方法 */publicclassBigInteger_{publicstaticvoidmain(String[] args){BigInteger bigInteger1 =newBigInteger("155646846846846");BigInteger bigInteger2 =newBigInteger("155646846846846");System.out.println(bigInteger2.add(bigInteger1));System.out.println(bigInteger2.subtract(bigInteger1));System.out.println(bigInteger2.multiply(bigInteger1));System.out.println(bigInteger2.divide(bigInteger1));}}日期类⭐
LocalTime、LocalDate、LocalDateTime
常见方法:
1.now: 静态方法,类调用,获取日期或时间或日期加时间字段 2.getYear() 3.getMonth():返回月份英文 4.getMonthValue():返回月份数字 5.getDayOfMonth():返回天 6.getHour() 7.getMinute() 8.getSecond() DateTimeFormatter格式日期类
类似于SimpleDateFormat
y 年 M 月 d 日 h 时(12) H 时(24) m 分 s 秒 E 星期几 测试
packagecom.lcz.commenclass.date;importjava.sql.Time;importjava.text.ParseException;importjava.text.SimpleDateFormat;importjava.time.Instant;importjava.time.LocalDate;importjava.time.LocalDateTime;importjava.time.LocalTime;importjava.time.chrono.ChronoLocalDate;importjava.time.format.DateTimeFormatter;importjava.util.Calendar;importjava.util.Date;/** * @author lcz * @version 1.0 * * 关于一二三代日期类相关方法使用 */publicclassDate_{publicstaticvoidmain(String[] args)throwsParseException{//第一代:Date//1.创建Date对象//无参创建System.out.println("=====第一代日期类Date=====");Date d1 =newDate();System.out.println("d1 = "+ d1);//以毫秒数创建Date d2 =newDate(1135153135);System.out.println("d2 = "+ d2);//SimpleDateFormat格式化日期类//(1):将Date对象格式化为字符串SimpleDateFormat sdf =newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");String format = sdf.format(d1);System.out.println("Date对象格式化为字符串: "+format);//(2):将字符串转化为对象String s ="1986-01-01 17:56:47";Date parse = sdf.parse(s);//sdf的格式化规则和字符串s不匹配,会报转化异常System.out.println("字符串转化为Date对象: "+parse);//第二代日期类:CalendarSystem.out.println("=====第二代日期类Calendar=====");Calendar c =Calendar.getInstance();System.out.println("c = "+ c);System.out.println(Calendar.YEAR);System.out.println(Calendar.MONTH);System.out.println(Calendar.DAY_OF_MONTH);System.out.println(Calendar.HOUR);System.out.println(Calendar.HOUR_OF_DAY);System.out.println(Calendar.MINUTE);System.out.println(Calendar.SECOND);//第三代日期类:LocalDateTime LocalDate LocalTimeLocalDateTime ldt =LocalDateTime.now();LocalDate ld =LocalDate.now();LocalTime lt =LocalTime.now();System.out.println(ldt.getYear());System.out.println(ldt.getMonth());System.out.println(ldt.getMonthValue());System.out.println(ldt.getDayOfMonth());System.out.println(ldt.getHour());System.out.println(ldt.getYear());System.out.println(ldt.getMinute());System.out.println(ldt.getSecond());//格式化日期类:DateTimeFormatterDateTimeFormatter dtf =DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");String format1 = dtf.format(ldt);System.out.println("格式化后的字符串 : "+ format1);//时间戳:Instant//(1):Date转化为InstantDate d3 =newDate();Instant instant = d3.toInstant();System.out.println("Date转化为时间戳: "+ instant);//(2):Instant转化为DateDate d4 =Date.from(instant);System.out.println("时间戳转化为Date对象: "+ d4);//提供plus和minus对当前时间进行加或减// 应用:如查看历史订单LocalDateTime ldt1 =LocalDateTime.now();LocalDateTime newldt = ldt1.plusDays(586);System.out.println(newldt);}}更多编程学习资源
编程学习公众号【程序员论周】