Java 第十五次作业
包裝類
?
包裝類 - 引入
【1】什么是包裝類:
以前定義變量,經(jīng)常使用基本數(shù)據(jù)類型
對于基本數(shù)據(jù)類型來說,它就是一個數(shù),加點(diǎn)屬性,加點(diǎn)方法,加點(diǎn)構(gòu)造器將基本數(shù)據(jù)類型對應(yīng)進(jìn)行了一個封裝,產(chǎn)生了一個新的類,---》包裝類。
int,byte..--->基本數(shù)據(jù)類型
包裝類--->引用數(shù)據(jù)類型
【2】對應(yīng)關(guān)系:
基本數(shù)據(jù)類型????????對應(yīng)的包裝類????????繼承關(guān)系?
byte??????????????????????????????Byte ???????????????---》Number---》Object?
short ????????????????????????????Short ?????????????---》Number---》Object?
int ????????????????????????????????Integer????????????---》Number---》Object?
long??????????????????????????????Long???????????? ? ---》Number---》Object
float ?????????????????????????????Float???????????????---》Number---》Object?
double? ? ? ? ? ? ? ? ? ? ? ? ? Double ???????? ? ---》Number---》Object?
char ?????????????????????????????Character???????? Object
boolean ???????????????????????Boolean????????????Object?
【3】已經(jīng)有基本數(shù)據(jù)類型了,為什么要封裝為包裝類?
(1)java語言面向?qū)ο蟮恼Z言,最擅長的操作各種各樣的類。
(2)以前學(xué)習(xí)裝數(shù)據(jù)的---》數(shù)組,int0]Stringldoublel StudentD
以后學(xué)習(xí)的裝數(shù)據(jù)的---》集合,有一個特點(diǎn),只能裝引用數(shù)據(jù)類型的數(shù)據(jù)
【4】是不是有了包裝類以后就不用基本數(shù)據(jù)類型了?
不是。
包裝類 - 常用屬性 - 常用構(gòu)造器
【1】直接使用,無需導(dǎo)包:
java. lang
類Integer
【2】類的繼承關(guān)系:
jara. lang. object
????????jaya.lang.Number
????????????????java. lang. integer
【3】實(shí)現(xiàn)接口:
所有已實(shí)現(xiàn)的接口;
Serializable,Comparable<Integer)
【4】這個類被final修飾,那么這個類不能有子類,不能被繼承:
pubilc?final class Integer
extends Number
implements Cosparable<Integer>
【5】包裝類是對基本數(shù)據(jù)類型的封裝:
對int類型封裝產(chǎn)生了Integer
Integer類在對象中包裝了一個基本類型int的值。
Integer類型的對象包含一個int類型的字段。
【6】類的歷史:
從以下版本開始:
????????JDK1.0
運(yùn)行結(jié)果如下:
?
【7】屬性:
//屬性:
System.out.println(IntegerMAXVALUE);?
System.out.println(IntegerMIN VALUE);
//"物極必反"原理:
System.out.println(Integer.MAX VALUE+1);
System.out.println(Integer.MIN VALUE-1);
【8】構(gòu)造器(發(fā)現(xiàn)沒有空參構(gòu)造器)
(1)int類型作為構(gòu)造器的參數(shù)
(2)String類型作為構(gòu)造器的參數(shù)
Integer i1 = new Integer(12);包裝類 - 自動裝箱 - 自動拆箱
【9]包裝類特有的機(jī)制:自動裝箱、自動拆箱:
//自動裝箱:int--->IntegerInteger i = 12;?System.out.println(i);//自動拆箱:Integer--->intInteger i2 = new Integer(12);int num = i2;System.out.println(num);(1)自動裝箱自動拆箱是從JDK1.5以后新出的特性
(2)自動裝箱自動拆箱:將基本數(shù)據(jù)類型和包裝類進(jìn)行快速的類型轉(zhuǎn)換。
驗(yàn)證:?
包裝類 - 常用方法
【10】Integer 常用方法
public class Test04 {//這是一個main方法,是程序的人口:public static void main(String[] args){//compareTo:只返回三個值:要么是0,-1,1 Integer i1 = new Integer(value:6); Integer i2 = new Integer( value:12);System.out.println(i1.compareTo(i2));// return(x<y)?-1:((x==y)?0:1)//eauals:Inteaer對Obiect中的eauals方法進(jìn)行了重寫,比較的是底層封裝的那個value的值。//Integer對象是通過new關(guān)鍵字創(chuàng)建的對象: Integer i3 = new Integer(value: 12); Integer i4 = new Integer(value: 12);System.out.println(i3 == i4);//false因?yàn)楸容^的是兩個對象的地址 boolean flag = i3.equals(i4); System.out.println(flag);//Integer對象通過自動裝箱來完成: Integer i5 = 130;Integer i6 = 130;System.out.println(i5.equals(i6));//true System.out.println(i5==i6);/*如果自動裝箱值在-128~127之間,那么比較的就是具體的數(shù)值否在,比較的就是對象的地址*///intValue():作用將Integer--->int Integer i7 = 130;int i= i7.intValue();System.out.println(i);//parseInt(String s) :String--->int: int i8=Integer parseInt(s:"12"); System.out.println(i8);//toString:Integer--->String Integer i10 = 130;System.out.println(i10.toString());} }日期相關(guān)
日期相關(guān) - java.util.Date
package zuoye15;import java.util.Date;public class Test { //這是一個main方法·是程序的人口:public static void main(String[] args){//java.util.Date:Date d=new Date(); System.out.println(d);System.out.println(d.toString());System.out.println(d.toGMTString());//過期方法·過時方法·廢棄方法。 System.out.println(d.toLocaleString());System.out.println(d.getYear());//122+1900=2022System.out.println(d.getMonth());//5:返回的值在日和11之間·值日表示1月//返回自1970年1月1日00:00:00GMT以來此Date對象表示的毫秒數(shù)。 System.out.println(d.getTime());//1592055964263 System.out.println(System.currentTimeMillis());/*(1)疑問:以后獲取時間差用:getTime()還是currentTimeMiLLis()答案:currentTimeMillis()--》因?yàn)檫@個方法是靜態(tài)的,可以類名,方法名直接調(diào)用(2)public static native long currentTimeMillis();本地方法為什么沒有方法體?因?yàn)檫@個方法的具體實(shí)現(xiàn)不是通過java寫的。*/} } /*(3)這個方法的作用:一般會去衡量一些算法所用的時間*/ public class Test { //這是一個main方法·是程序的人口:public static void main(String[] args){long startTime = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) {System.out.println(i);long endTime=System.currentTimeMillis(); System.out.println(endTime-startTime);}} }日期相關(guān) - java.sql.Date
(使用 IDEA)
import java.sql.Date;public class Text {public static void main(String[] args){//java.sql.Date:Date d = new Date(1592055964263L);System.out.println(d);/*(1)java.sql.Date和java.util.Date的區(qū)別:java.util.Date: 年月日 時分秒java.sql.Date: 年月日(2)java.sql.Date和java.utilDate的聯(lián)系:java.sql.Date(子類) extends java.util.Date(父類)*///java.sql.Date和java.util.Date相互轉(zhuǎn)換://【1】util--->sqL:java.util.Date date = new Date(1592055964263L);//創(chuàng)建util.Date的對象//方式1:向下轉(zhuǎn)型Date date1=(Date) date;/*父類:Animal 子類:DogAnimal an =new Dog();bog d=(Dog)an;*///方式2:利用構(gòu)造器Date date2 = new Date(date.getTime());//【2】sql-->util:java.util.Date date3=d;//[3]String--->sqL.Date:Date date4 = Date.valueOf("2020-5-7");} }日期相關(guān) -?SimpleDateFormat
【1】String---》java.util.Date類型轉(zhuǎn)換:
分解:
(1)String--->java.sql.Date
(2)java.sql.Date--->java.util.Date
上面的代碼有局限性,字符串的格式只能是年-月-日拼接的形式,換成其它類型,就會出現(xiàn)異常:?
【2】引入新的類:
package zuoye15;import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;public class Test05 {//這是一個main方法,是程序的入口:public static void main(String[] args){//日期轉(zhuǎn)換://SimpleDateFormat(子類) extends DateFormat(父類是一個抽象類)//格式化的標(biāo)準(zhǔn)已經(jīng)定義好了:DateFormat df =new SimpleDateFormat( pattern:"yyyy-MM-ddHH:mm:ss");//String--->Datetry {Date d=df.parse( source:"2019-4-6 12:23:54"); System.out.println(d);} catch (ParseException e){e.fillInStackTrace();}//Date--->StringString format=df.format(newDate()); System.out.println(format);Date date = new Date();System.out.println(date.toString()); System.out.println(date.toGMTString());System.out.println(date.toLocaleString());}private static Date newDate() {// TODO Auto-generated method stubreturn null;} }日期相關(guān) -?Calendar
import java.util.Calendar;import java.util.GregorianCalendar;public class Test06 {//這是一個main方法,是程序的入口:public static void main(String[] args) {//Calendar是一個抽象類,不可以直接創(chuàng)建對象//GregorianCalendar()子類extendsCalendar(父類是一個抽象類)Calendar cal=new GregorianCalendar();Calendar cal2=Calendar.getInstance();System.out.println(cal);//常用的方法://get方法,傳入?yún)?shù):Calendar中定義的常量System.out.println(cal.get(Calendar.YEAR)); System.out.println(cal.get(Calendar.MONTH)); System.out.println(cal.get(Calendar.DATE));System.out.println(cal.get(Calendar.DAY_OF_WEEK));System.out.println(cal.getActualMaximum(Calendar.DATE));//獲取當(dāng)月日期的最大天數(shù) System.out.println(cal.getActualMinimum(Calendar.DATE));//獲取當(dāng)月日期的最小天數(shù)// set方法:cal.set(Calendar.YEAR,1990);cal.set(Calendar.MONTH,3);cal.set(Calendar.DATE,16);System.out.println(cal);//String--->Calendar:/1分解://String--->java.sql.Date:java.sql.Date date = java.sql.Date.valueOf("2022-5-7");//java.sql.Date-->Calendar: cal.setTime(date);System.out.println(cal);} }?運(yùn)行結(jié)果如下:
日期相關(guān) -?Calendar練習(xí) :
解:
import java.util.Calendar; import java.util.Scanner;public class Test08 {//這是一個main方法,是程序的入口:public static void main(String[] args) {//錄入日期的string:Scanner sc=new Scanner(System.in);System.out.print("請輸入你想要查看的日期:(提示:請按照例如2012-5-6的格式書寫)");String strDate=sc.next();//System.out.println(strDate);//String--->Calendar:// String-->Date:java.sql.Date date = java.sql.Date.valueOf(strDate);//Date--->Calendar:Calendar cal=Calendar.getInstance(); cal.setTime(date);//后續(xù)操作:// 星期提示:System.out.println("日\t一\t二\t三\t四\t五\t六\t");//獲取本月的最大天數(shù):int maxDay=cal.getActualMaximum(Calendar.DATE);//獲取當(dāng)前日期中的日:int nowDay=cal.get(Calendar.DATE);//將日期調(diào)為本月的1號:cal.set(Calendar.DATE,1);//獲取這個一號是本周的第幾天int num =cal.get(Calendar.DAY_OF_WEEK);//System.out.println(num);//前面空出來的天數(shù)為:int day =num -1;//引入一個計(jì)數(shù)器:int count=0;//計(jì)數(shù)器最開始值為0//在日期前將空格打印出來:for (int i = 1; i <= day; i++) {System.out.print("\t");}//空出來的日子也要放入計(jì)數(shù)器 count = count + day;count = count +day;//遍歷:從1號開始到maxDay號進(jìn)行遍歷:for (int i = 1; i <= maxDay ;i++) {if(i==nowDay){//如果遍歷的和當(dāng)前日子一樣的話,后面多拼一個*System.out.print(i+"*"+"\t");}else{System.out.print(i+"\t");}count++;//每在控制臺輸出一個數(shù)字,計(jì)數(shù)器做加1操作if(count%7 == 0){//當(dāng)計(jì)數(shù)器的個數(shù)是7的倍數(shù)的時候,就換行操作System.out.println();}}} }運(yùn)行結(jié)果如下:
?
日期相關(guān) - JDK1.8新增日期時間API的原因
JDK1.0中使用iava.util.Date類--》第一批日期時間API
JDK1.1引入Calendar類--》第二批日期時間API
缺陷:
可變性:像日期和時間這樣的類應(yīng)該是不可變的。
偏移性:Date中的年份是從1900開始的,而月份都從0開始。
格式化:格式化只對Date有用,Calendar則不行。
JDK1.8新增日期時間API--》第三批日期時間API
日期相關(guān) - JDK1.8新增日期時間API -?LocaLDate,LocaLTime,LocalDateTime
LocaLDate:日期
LocaLTime:時間
LocalDateTime:日期+時間
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime;public class Test09 {//這是一個main方法,是程序的入口:public static void main(String[] args) {//1.完成實(shí)例化:// 方法1:now()--獲取當(dāng)前的日期,時間 日期+時間LocalDate localDate=LocalDate.now();System.out.println(localDate);LocalTime localTime = LocalTime.now();System.out.println(localTime);LocalDateTime localDateTime=LocalDateTime.now();System.out.println(localDateTime);//方法2:of()--設(shè)置指定的日期,時間,日期+時間LocalDate of = LocalDate.of(2010,5,6);System.out.println(of);LocalTime of1 = LocalTime.of(12,35,56);System.out.println(of1);LocalDateTime of2 = LocalDateTime.of(1890,12,23,13,24,15);System.out.println(of2);//LocaLDate,LocaLTime用的不如LocalDateTime多// 下面講解用LocaLDateTime:// 一系列常用的get***System.out.println(localDateTime.getYear());//年System.out.println(localDateTime.getMonth());//月(英語)System.out.println(localDateTime.getMonthValue());//月(數(shù)字)System.out.println(localDateTime.getDayOfMonth());//日System.out.println(localDateTime.getDayOfWeek());//星期System.out.println(localDateTime.getHour());//時System.out.println(localDateTime.getMinute());//分System.out.println(localDateTime.getSecond());//秒//不是set方法,叫with//體會:不可變性LocalDateTime localDateTime2=localDateTime.withMonth(8);System.out.println(localDateTime);System.out.println(localDateTime2);//提供了加減的操作:// 加:LocalDateTime localDateTime1=localDateTime.plusMonths(4);System.out.println(localDateTime);System.out.println(localDateTime1);//減:LocalDateTime localDateTime3=localDateTime.minusMonths(5);System.out.println(localDateTime);System.out.println(localDateTime3);} }運(yùn)行結(jié)果如下:
日期相關(guān) -?DateTimeFormatter
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.time.temporal.TemporalAccessor;public class Test10 {//這是一個main方法,是程序的入口:public static void main(String[] args) {//格式化類:DateTimeFormatter//方式一:預(yù)定義的標(biāo)準(zhǔn)格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIMEDateTimeFormatter df1 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;//df1就可以幫我們完成LocalDateTime和string之間的相互轉(zhuǎn)換:// LocalDateTime-->String:LocalDateTime now=LocalDateTime.now();String str = df1.format(now);System.out.println(str);//2020-06-15T15:02:51.29//String--->LocalDateTimeTemporalAccessor parse = df1.parse("2020-06-15T15:02:51.29");System.out.println(parse);//方式二:本地化相關(guān)的格式。如:ofLocalizedDateTime()//參數(shù):FormatStyle.LONG/FormatStyle.MEDIUM/FormatStyle.SHORT// FormatStyle.LONG:2020年6月15日下午03時17分13秒// FormatStyle.MEDIUM:2022年5月7日 下午9:13:25// FormatStyle.SHORT:2022/5/7 下午9:02DateTimeFormatter df2 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);//LocalDateTime-->String:LocalDateTime now1 = LocalDateTime.now();String str2 = df2.format(now1);System.out.println(str2);//String--->LocalDateTimeTemporalAccessor parse1 = df2.parse("2022/5/7 下午9:02");System.out.println(parse1);//方式三:自定義的格式。如:ofPattern("yyyy-MM-dd hh:mm:ss")---》重點(diǎn),以后常用DateTimeFormatter df3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm;ss");//LocalDateTime-->String:LocalDateTime now2 = LocalDateTime.now();String format = df3.format(now2);System.out.println(format);//2020-06-15 03:22:03//String--->LocalDateTimeTemporalAccessor parse2 = df3.parse("2022-05-07 09:15;34");System.out.println(parse2);} }運(yùn)行結(jié)果如下:
Math 類
【1】直接使用,無需導(dǎo)包:
package java.lang;
【2】final修飾類,這個類不能被繼承:
public final class Math {?
}
【3】構(gòu)造器私有化,不能創(chuàng)建Math類的對象:
/** * Don't let anyone instantiate this class.*/ private Math() {}不能:
public static void main(String[] args) {Math m=new Math();}【4】Math內(nèi)部的所有的屬性,方法都被static修飾:類名.直接調(diào)用,無需創(chuàng)建對象:
Math.java
public static final double PI = 3.14159265358979323846;
/**
* Returns the trigonometric sine of an angle. Special cases:<ul><li>If the argument is NaN * * or an infinity, then the* result is NaN.
* <li>If the argument is zero, then the result is a zero with the same sign as the argument.? ? * </ul>
*
* <p>The computed result must be within 1 ulp of the exact result.* Results must be semi-
* monotonic.
*
* @param????????a????????an angle, in radians.?
* @return the sine of the argument.
*/
@Contract(pure=true) public static double sin(double a) { return StrictMath.sin(a)}
【5】常用方法:
public class Test01 {//這是一個main方法,是程序的入口:?public static void main(String[] args) {//常用屬性:System.out.println(Math.PI);//常用方法:System.out.println("隨機(jī)數(shù):"+Math.random());//[0.0,1.0)System.out.println("絕對值:"+Math.abs(-80));System.out.println("向上取值:"+Math.ceil(9.1));System.out.println("向下取值:"+Math.floor(9.9));System.out.println("四舍五入:"+Math.round(3.5));System.out.println("取大的那個值:"+Math.max(3,6));System.out.println("取小的那個值:"+Math.min(3,6));} }
運(yùn)行結(jié)果如下:
【6】靜態(tài)導(dǎo)入
package zuoye15;import static java.lang.Math.*;public class Test01 {//這是一個main方法,是程序的入口:public static void main(String[] args) {//常用屬性:System.out.println(PI);//常用方法:System.out.println("隨機(jī)數(shù):"+random());//[0.0,1.0) System.out.println("絕對值:"+abs(-80));System.out.println("向上取值:"+ceil(9.1)); System.out.println("向下取值:"+floor(9.9)); System.out.println("四舍五入:"+round(3.5)); System.out.println("取大的那個值:"+max(3,6)); System.out.println("取小的那個值:"+min(3,6));} //如果跟Math中方法重復(fù)了,那么會優(yōu)先走本類中的方法(就近原則) public static int random(){return 100;} }
運(yùn)行結(jié)果如下:
Random 類
隨機(jī)數(shù):
package zuoye15;import java.util.Random;public class Test02 {//這是一個main方法,是程序的入口:public static void main(String[] args) {//返回帶正號的 double 值,該值大于等于0.0 且小于 1.0。 System.out.println("隨機(jī)數(shù):"+Math.random());//學(xué)習(xí)Random類//(1)利用帶參數(shù)的構(gòu)造器創(chuàng)建對象:Random r1 =new Random(System.currentTimeMillis()); int i=r1.nextInt();System.out.println(i);//(2)利用空參構(gòu)造器創(chuàng)建對象:Random r2 =new Random();//表面是在調(diào)用無參數(shù)構(gòu)造器,實(shí)際底層還是調(diào)用了帶參構(gòu)造器System.out.println(r2.nextInt(10));//在0(包括)和指定值(不包括)之間均勻分布的 int值。 System.out.println(r2.nextDouble());//在0.0和 1.0之間均勻分布的 double 值。} }運(yùn)行結(jié)果如下:
String 類
String 的本質(zhì)
?
?
String 的常用方法
【1】構(gòu)造器:底層就是給對象底層的value數(shù)組進(jìn)行賦值操作。
通過構(gòu)造器來創(chuàng)建對象:?
String s1 = new String();
String s2 = new String("abc");
String s3 = new String(new char[] {'a' 'b' 'c'});
【2】常用方法
String s4 = "abc";
System.out.println("字符串的長度為:"+s4.length());
String s5 =new String("abc");
System.out.println("字符串是否為空:"+s5.isEmpty());
System.out.println("獲取字符串的下標(biāo)對應(yīng)的字符為:"+s5.charAt(1));
【3】equals:
String s6 = new String("abc");
String s7 = new String("abc");
System.out.println(s6.equals(s7));
比較字符串是否相等:
【4】String類實(shí)現(xiàn)了Comparable,里面有一個抽象方法叫compareTo,所以String中一定要對這個方法進(jìn)行重寫:
String s8 = new string("abc");
String s9 = new string("abc");
System.out.println(s8.compareTo(s9));
【5】其他常用方法
//字符串的截取:
String s10 = "abcdefhijk";
System.out.println(s10.substring(3));
System.out.println(s10.substring(3,6));//[3,6)
//字符串的合并/拼接操作:
System.out.println(s10.concat("pppp"));
//字符串中的字符的替換:
String s11 = "abcdeahija";
System.out.println(s11.replace( oldChar: 'a', newChar: 'u'));
//按照指定的字符串進(jìn)行分裂為數(shù)組的形式:
String s12 = "a-b-c-d-e-f";
String[] strs = s12.split( regex: "-");
System.out.println(Arrays.toString(strs));
//轉(zhuǎn)大小寫的方法:
String s13 = "abc";
System.out.println(s13.toUpperCase());
System.out.println(s13.toUpperCase().toLowerCase())
//去除收尾空格:
String s14 =" abc ";?
System.out.println(s14.trim());//tostring()
string s15="abc";
System.out.println(s15.tostring());
//轉(zhuǎn)換為string類型:
System.out.println(string.valueOf(false));
String 的內(nèi)存分析
【1】字符串拼接:
public class Test02 {//這是一個main方法,是程序的入口:?public static void main(string[] args) {String s1 = "a"+"b"+"c";String s2 = "ab"+"c"; string s3 = "a"+"bc";String s4 = "abc";String s5 = "abc"+"".}}上面的字符串,會進(jìn)行編譯器優(yōu)化,直接合并成為完整的字符串,我們可以反編譯驗(yàn)證:
然后在常量池中,常量池的特點(diǎn)是第一次如果沒有這個字符串,就放進(jìn)去,如果有這個字符串,就直接從常量池中取:
內(nèi)存:
【2】new關(guān)鍵字創(chuàng)建對象:
?String s6 = new string("abc");
內(nèi)存:開辟兩個空間(1.字符串常量池中的字符串2.堆中的開辟的空間)
【3】有變量參與的字符串拼接:
public class Test03 {//這是一個main方法,是程序的入口:?public static void main(string[] args) {String a ="abc".String b = a + "def";System.out.println(b);}? }a變量在編譯的時候不知道a是“abc”字符串,所以不會進(jìn)行編譯期優(yōu)化,不會直接合并為“abcdef”
反匯編過程:?為了更好的幫我分析字節(jié)碼文件是如何進(jìn)行解析的:
利用IDEA中的控制臺:
StrinngBuilder 類
【1】字符串的分類:
(1)不可變字符串:String
(2)可變字符串:StringBuilder,StringBuffer
疑問:
(1)可變不可變??
(2)本節(jié)課重點(diǎn):StringBuilder -----》√(3)StringBuilder和StringBuffer區(qū)別 ??
【2】StringBuilder底層:非常重要的兩個屬性:
?
【3】對應(yīng)的內(nèi)存分析
public class Test01 {//這是一個main方法,是程序的入口:public static void main(String[] args) {//創(chuàng)建StrinqBullder的對象:StringBuilder sb3 = new StringBuilder();//表面上調(diào)用StrinqBuilder的空構(gòu)造器,實(shí)際底層是對value數(shù)組進(jìn)行初始化,長度為16StringBuilder sb2 =new StringBuilder(3);//表面上調(diào)用StringBuilder的有參構(gòu)造器,傳入一個int類型的數(shù),實(shí)際底層就是對 ivalue數(shù)組進(jìn)行初始化,長度為你傳入的數(shù)字StringBuilder sb = new StringBuilder("abc");sb.append("def") . append("aaaaaaaa"). append("bbb").append("ooooooo");//鏈?zhǔn)秸{(diào)用方式: return thisSystem.out.println(sb.append("def") . append("aaaaaaaa"). append("bbb").append("ooooooo"));} }運(yùn)行結(jié)果如下:
?
?
String 和 StringBuilder
【1】String ——> 不可變
?
【2】StringBuilder ——> 可變
可變,在StringBuilder這個對象的地址不變的情況下,想把“abc”變成“abcdef”是可能的,直接追加即可
運(yùn)行結(jié)果如下:
?
StringBuilder 和 StringBuffer
StringBuilder常用方法:
public class Test03 {//這是一個main方法,是程序的入口:public static void main(String[] args) {StringBuilder sb=new StringBuilder("nihaojavawodeshijie");//增sb.append("這是夢想");System.out.println(sb);//nihaojavawodeshijie這是夢想// 刪sb.delete(3, 6);//刪除位置在[3,6)上的字符System.out.println(sb);//nihavawodeshijie這是夢想sb.deleteCharAt(16);//刪除位置在16上的字符System.out.println(sb);//nihavawodeshijie是夢想//改-->插入StringBuilder sb1=new StringBuilder("$23445980947");sb1.insert(3, ",");//在下標(biāo)為3的位置上插入,System.out.println(sb1);StringBuilder sb2=new StringBuilder("$2你好嗎5980947");//改-->替換sb2.replace(3,5,"我好累");//在下標(biāo)[3,5)位置上插入字符串System.out.println(sb2);sb.setCharAt(3,'!');System.out.println(sb);//查StringBuilder sb3=new StringBuilder("asdfa");for (int i = 0; i<sb3.length(); i++) {System.out.print(sb3.charAt(i)+"\t");}System.out.println();//截取String str=sb3.substring(2,4);//截取[2,4)返回的是一個新的String,對StringBuilder沒有影響System.out.println(str);System.out.println(sb3);} }運(yùn)行結(jié)果如下:
?
StringBuffer常用方法:
public class Test03 {//這是一個main方法,是程序的入口:public static void main(String[] args) {StringBuffer sb=new StringBuffer("nihaojavawodeshijie");//增sb.append("這是夢想");System.out.println(sb);//nihaojavawodeshijie這是夢想// 刪sb.delete(3, 6);//刪除位置在[3,6)上的字符System.out.println(sb);//nihavawodeshijie這是夢想sb.deleteCharAt(16);//刪除位置在16上的字符System.out.println(sb);//nihavawodeshijie是夢想//改-->插入StringBuilder sb1=new StringBuilder("$23445980947");sb1.insert(3, ",");//在下標(biāo)為3的位置上插入,System.out.println(sb1);StringBuilder sb2=new StringBuilder("$2你好嗎5980947");//改-->替換sb2.replace(3,5,"我好累");//在下標(biāo)[3,5)位置上插入字符串System.out.println(sb2);sb.setCharAt(3,'!');System.out.println(sb);//查StringBuilder sb3=new StringBuilder("asdfa");for (int i = 0; i<sb3.length(); i++) {System.out.print(sb3.charAt(i)+"\t");}System.out.println();//截取String str=sb3.substring(2,4);//截取[2,4)返回的是一個新的String,對StringBuffer沒有影響System.out.println(str);System.out.println(sb3);} }運(yùn)行結(jié)果如下:
String、StringBuffer、StringBuilder區(qū)別與聯(lián)系
1、String類是不可變類,即一日一個String對象被創(chuàng)建后,包含在這個對象中的字符序列是不可改變的,直至這個對象銷毀。
2、StringBuffer類則代表一個字符序列可變的字符串,可以通過append、insert、reverse、setChartAt、setLength等方法改變其內(nèi)容。一旦生成了最終的字符串,調(diào)用toString方法將其轉(zhuǎn)變?yōu)镾tring。
3、JDK1.5新增了一個StringBuilder類,與StringBuffer相似,構(gòu)造方法和方法基本相同。不同是StringBuffer是線程安全的,而StringBuilder是線程不安全的,所以性能略高。通常情況下,創(chuàng)建一個內(nèi)容可變的字符串,應(yīng)該優(yōu)先考慮使用StringBuilder。
注:
StringBuilder:JDK1.5開始 效率高線程不安全
StringBuffer:JDK1.0開始效率低線程安全
總結(jié)
以上是生活随笔為你收集整理的Java 第十五次作业的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 热题 HOT 100
- 下一篇: JavaWeb中 pojo、entity