




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
程序設(shè)計第7章常用實用類目錄2
7.1常用工具類
7.2Java集合容器
7.3List接口
7.4Set接口
7.5Map接口7.1.1String類字符串常量使用雙引號""定義字符串,使用單引號''定義字符。字符串幾乎可以任意長(從0至231,約20億)。字符串類String類StringBuffer類37.1.1String類String類的聲明和初始化聲明字符串變量初始化字符串直接賦值,例如:使用構(gòu)造方法,例如:String類實例的值為空和空串是不同的:4 str="abc"; //直接賦值 Stringstr2=newString(); //創(chuàng)建長度為0的字符串 Stringstr5=null; //str5的值為空(也是默認值),它沒有值 intlen=str5.length();//沒有長度,因此運行時出現(xiàn)異常 Stringstr6=""; //str6的值為空串,它有值,只是長度為0 len=str6.length(); //長度為0String類的常用方法字符串的長度String類的length()方法返回字符串的長度Stringstr="你好,Java!";intlen=str.length();//長度為8(其中3個漢字或中文標點,5個字母符號)System.out.println("字符串的長度為:"+len);字符串的比較必須使用equals()方法而不是==號來比較字符串的值Stringstr1="Java";//如果內(nèi)存中沒有"Java"常量,則創(chuàng)建它Stringstr2="Java";//內(nèi)存中已有"Java"常量,所以str2指向它Stringstr3=newString("Java");//新創(chuàng)建一個值為"Java"的常量Stringstr4=newString("Java");//新創(chuàng)建一個值為"Java"的常量booleanb1=str1==str2;//true,str1和str2指向同一個字符常量booleanb2=str2==str3;//false,str2和str3指向不同的字符常量booleanb3=str3==str4;//false,str3和str4指向不同的字符常量booleanb=str1.equals(“str2");//true5String類的常用方法字符串的比較String類的compareTo()方法和compareToIgnoreCase()方法比較字符串的大小,它返回一個int型的整數(shù),表示兩個字符串在某個字符處的Unicode碼的差值。Strings1="123a";Strings2="123A";Strings3="123B";intresult1=pareTo(s2); //32,即'a'-'A'的值intresult2=pareToIgnoreCase(s3);//-1,轉(zhuǎn)換為小寫后,'a'-'b'的值6String類的常用方法字符串的連接String類的concat()方法將指定字符串聯(lián)到此字符串的末尾。用“+”也可以達到同樣的目的,而且更為常用。Stringstr="Java";Strings1=str.concat("programming.");Strings2=str+"programming."; //與concat()等價String類的常用方法(續(xù))字符串的檢索字符串的子串字符串的替換字符串轉(zhuǎn)換大小寫8
Stringstr="MyEclipse.exe";Strings1=str.toUpperCase();//MYECLIPSE.EXEStrings2=str.toLowerCase();//myeclipse.exe
Stringstr="Javaprogramming.";
Strings2=str.replace("pro","Pro");//JavaProgramming.
Stringstr="MyEclipse.exe";
Strings2=str.substring(2,9);//Eclipse
Strings1="這是Java程序。";charc2=s1.charAt(7);//序【例7.1】String類的使用示例。public
classStringDemo{public
static
voidmain(String[]args){Stringstr="你好,Java!";int
len=str.length();//長度為8System.out.println("字符串的長度為:"
+len);str
="Java";boolean
b1=str.equals("java");//大小寫敏感時為falseboolean
b2=str.equalsIgnoreCase("java");//大小寫不敏感時為trueboolean
b3="java".equals("java");//trueSystem.out.println("Java和java是否相等"
+b1);System.out.println("大小寫不敏感時Java和java是否相等"
+b2);System.out.println("java和java是否相等"
+b3);Strings1="123a";Strings2="123A";Strings3="123B";int
result1=s1.compareTo(s2);//32,即'a'-'A'的值int
result2=s1.compareToIgnoreCase(s3);//'a'-'b'的值為-1System.out.println("123a與123A比較:"
+result1);System.out.println("忽略大小寫時123a與123B比較:"
+result2);
}}9String類的特殊性所有引用數(shù)據(jù)類型都必須使用new操作符創(chuàng)建,而字符串類型還能通過直接賦值創(chuàng)建。字符串常量是一個對象,因此可以調(diào)用字符串常量的方法,如"Java!".length()。字符串類型屬于引用數(shù)據(jù)類型,但在方法調(diào)用時,采用的是傳值調(diào)用。字符串類型可以用加號“+”運算符,將字符串類的對象與其它各種類型(基本或引用數(shù)據(jù)類型)的對象連接。字符串類型可以用賦值運算符“=”和“+=”進行賦值。字符串的值本身是常量,是不可變的。107.1.2StringBuffer類字符串StringBuffer類(緩沖型字符串類)可變長的和可寫的字符序列其中除字符序列之外還含有預留空間直接在字符序列上進行追加、插入或刪除操作StringBuffer構(gòu)造方法(只能使用構(gòu)造方法創(chuàng)建)11
StringBuffersb1=newStringBuffer();//長度為0,容量為16(默認值)StringBuffersb2=newStringBuffer(50);//長度為0,容量為50StringBuffersb3=newStringBuffer("Java");//長度為4,容量為20(=4+16)長度與緩沖區(qū)容量長度String類和StringBuffer類都有l(wèi)ength()方法緩沖區(qū)容量(僅StringBuffer類)方法capacity()返回StringBuffer實例的緩沖區(qū)容量。方法ensureCapacity()確保容量至少等于指定的最小值。新緩沖區(qū)容量取下述二者的較大值:參數(shù)minCapacity的值。原有容量的兩倍加2。12
StringBuffersb1=newStringBuffer();//長度為0,容量為16StringBuffersb2=newStringBuffer(50);//長度為0,容量為50StringBuffersb3=newStringBuffer("Java");//長度為4,容量為16+4=20
sb1.ensureCapacity(60);//長度0,容量60,因為16*2+2=34<60sb2.ensureCapacity(60);//長度0,容量102,因為50*2+2=102>60sb3.append("12345678901234567890");//長度4+20=24,容量=2*20+2=42StringBuffer類的比較無法比較StringBuffer類的值不能用==也不能用equals()方法只能將它們轉(zhuǎn)換為String類,然后進行比較13
StringBuffersb1=newStringBuffer("Java");StringBuffersb2=newStringBuffer("Java");booleanb1=sb1==sb2;//false,不能用==booleanb2=sb1.equals(sb2);//false,也不能用equals()booleanb3=sb1.toString().equals(sb2.toString());//true7.1.2StringBuffer類14String類和StringBuffer類的比較String類在內(nèi)存中的表現(xiàn)字符串的值本身是常量,是不可變的,例如:15
Strings2="abc";
//指向已有的字符串值System.out.println(s1==s2);//返回true
Strings1="abc";//在SLP中創(chuàng)建"abc"
Strings1="abc";//在SLP中創(chuàng)建
s1=s1+"123";//在SLP中創(chuàng)建"abc123"值“abc”是不變的值“abc”不再被使用時,將被垃圾回收機制回收比較(二)StringBuffer類在內(nèi)存中的表現(xiàn)16 StringBuffersb1=newStringBuffer("abc"); sb1.append("123");在緩沖內(nèi)添加,因此值“abc”可被修改比較(三)String類和StringBuffer類的互換String轉(zhuǎn)換為StringBuffer:StringBuffer轉(zhuǎn)換為String:適用的場合String類使用方便,效率低,用于一般場合StringBuffer類使用不方便,但效率高,用于大量的字符處理,如循環(huán)中17
StringBuffersb=newStringBuffer("Java");Strings=sb.toString();
Strings="abc";StringBuffersb=newStringBuffer(s);【例7.2】StringBuffer類的使用示例。public
classStringBufferDemo{public
static
voidmain(String[]args){StringBufferbuffer=newStringBuffer("Hello,");buffer.append("Java!").append("歡迎!");System.out.println(buffer);//刪除索引為5的標點符號buffer.deleteCharAt(5);System.out.println(buffer);//在索引為5的位置上插入“你好”buffer.insert(5,"你好");System.out.println(buffer);//將buffer的內(nèi)容反轉(zhuǎn)buffer.reverse();System.out.println(buffer);}}187.2Java集合容器集合容器類共分為兩類:集合(Collection):一個集合就是存儲一組對象的容器。Set(集):集合中的對象(也稱為元素element)沒有次序之分,且沒有重復對象。List(列表):集合中的對象按照索引位置排序,可以有重復對象,可以按索引位置檢索對象。映射(Map):集合中的每個對象都由一個特殊的“鍵-值”對組成。鍵對象不能重復,值對象可以重復。197.2Java集合容器207.3Collection接口21【例7.3】Collection接口示例。public
classCollectionDemo{public
static
voidmain(String[]args){//創(chuàng)建集合對象Collectioncollection=newArrayList();//添加集合中的元素collection.add("Hi");collection.add(123);System.out.println("集合中元素個數(shù)為:"
+collection.size());//判斷是否包含字符串Hiboolean
isContains=collection.contains("Hi");System.out.println("是否包含Hi:"+isContains);//判斷集合是否為空boolean
isEmpty=collection.isEmpty();System.out.println("集合是否為空:"
+isEmpty);//移除元素后,現(xiàn)有元素個數(shù)collection.remove("Hi");System.out.println("移除Hi后元素個數(shù)為:"
+collection.size());//清空操作collection.clear();System.out.println("清空操作后元素個數(shù):"
+collection.size());}}227.3.1Iterator接口遍歷集合中的所有元素:Iterator迭代器booleanhasNext():判斷是否存在另一個可以訪問的元素Objectnext():返回下一個可以訪問的元素。通常與hasNext()方法結(jié)合使用,以免產(chǎn)生異常。Iteratoriterator=collection.iterator(); //遍歷集合中的所有元素 while(iterator.hasNext()){ Objectobj=iterator.next(); System.out.println(obj); }23【例7.4】Iterator示例。public
classIteratorDemo{public
static
voidmain(String[]args){//創(chuàng)建集合對象Collectioncollection=newArrayList();//添加集合中的元素collection.add("Hi");collection.add(123);//獲得一個迭代器對象Iteratoriterator=collection.iterator();//遍歷集合中的所有元素while(iterator.hasNext()){Objectobj=iterator.next();System.out.println(obj);}}}247.3.2foreach循環(huán)foreach增加型for循環(huán),用于遍歷數(shù)組或集合中的元素for(容器中的對象類型臨時變量名:容器變量){
執(zhí)行語句}//用foreach遍歷集合中的所有元素 for(Object
obj:collection){ System.out.println(obj); }25【例7.5】增強型for示例。public
classForeachDemo{public
static
voidmain(String[]args){//創(chuàng)建集合對象Collectioncollection=newArrayList();collection.add("Hi");collection.add(123);//用foreach遍歷集合中的所有元素for(Objectobj:collection){System.out.println(obj);}}}267.3List接口【例7.6】ArrayList示例。public
classArrayListDemo{public
static
voidmain(String[]args){//創(chuàng)建ArrayList對象listListlist=newArrayList();//將指定元素添加到列表尾部list.add("小王");list.add("小張");list.add("小李");list.add("小陳");list.add("小趙");//獲取容器中元素的個數(shù)System.out.println("集合中元素個數(shù)是:"
+list.size());//遍歷表中的所有元素Iteratorit=list.iterator();while
(it.hasNext()){Objectobj=it.next();System.out.print(obj
+"");}System.out.println();28【例7.6】ArrayList示例。29//在指定位置2插入重復元素“小陳”list.add(2,"小陳");//顯示指定位置2的元素System.out.println("指定位置2的元素是:"
+list.get(2));//將位置5改為“小趙2”list.set(5,"小趙2");//遍歷方法2System.out.println("添加修改后,列表中的元素有:");for(int
i=0;i<list.size();i++){System.out.print(list.get(i)+"");}System.out.println();//返回“小陳”首次出現(xiàn)的位置System.out.println("小陳首次出現(xiàn)的位置"
+list.indexOf("小陳"));//返回“小陳”最后出現(xiàn)的位置System.out.println("小陳最后出現(xiàn)的位置"
+list.lastIndexOf("小陳"));【例7.6】ArrayList示例。//移除指定位置2的元素,并將移除元素輸出Objectobj=list.remove(2);System.out.println("移除元素是:"
+obj);//移除指定元素“小趙2”boolean
b=list.remove("小趙2");System.out.println(b);//將列表轉(zhuǎn)換成數(shù)組,并用數(shù)組展示System.out.println("移除元素后,列表中的元素有:");Object[]arr=list.toArray();for(int
i=0;i<arr.length;i++){System.out.print(arr[i]+"");}System.out.println();//清空列表元素,并輸出元素個數(shù)list.clear();System.out.println("列表清空后的元素個數(shù)是:"
+list.size());}}30【例7.7】LinkedList類示例。使用LinkedList模擬棧結(jié)構(gòu)。public
classMyStack{//創(chuàng)建LinkedList對象LinkedListlinkedList=newLinkedList();//入棧public
voidpush(Objecto){linkedList.addFirst(o);}//出棧publicObjectpop(){return
linkedList.removeFirst();}//獲取棧頂元素publicObjectpeek(){return
linkedList.getFirst();}//棧是否為空public
booleanempty(){return
linkedList.isEmpty();}}【例7.7】LinkedList類示例。使用LinkedList模擬棧結(jié)構(gòu)。public
classTestMyStack{public
static
voidmain(String[]args){//定義棧MyStackstack=newMyStack();//入棧插入三個元素stack.push("小王");stack.push("小張");stack.push("小李");//出棧System.out.println("出棧元素:"
+stack.pop());//顯示棧頂元素System.out.println("棧頂元素:"
+stack.peek());//出棧System.out.println("出棧元素:"
+stack.pop());//判斷棧是否為空System.out.println(stack.empty());}}7.4Set接口
33【例7.8】HashSet示例。public
classSetDemo{public
static
voidmain(String[]args){Setset=newHashSet();set.add("李明");set.add("劉麗");System.out.println("set中的元素有:");Iteratorit=set.iterator();while(it.hasNext()){Objectobj=it.next();System.out.println(obj);}Set.add("劉麗");//添加相同的元素set.add(123);System.out.println("加入兩個元素后,set中有:");it=set.iterator();while(it.hasNext()){Objectobj=it.next();System.out.println(obj);}}}34【例7.9】TreeSet類示例。public
classCustomerimplementsComparable{privateStringname;private
int
age;//此處省略getters()、setters()方法和構(gòu)造方法@Overridepublic
intcompareTo(Objectarg0){Customerother=(Customer)arg0;if(this.getName().compareTo(other.getName())>0){return1;}else
if(this.getName().compareTo(other.getName())<0){return-1;}else{if(this.age>other.age){return1;}else
if(this.age<other.age){return-1;}else{return0;}}}【例7.9】TreeSet類示例。public
classTreeSetTest2{public
static
voidmain(String[]args){//定義一個TreeSet對象Setset=newTreeSet();Customerc1=newCustomer("zs",18);Customerc2=newCustomer("zs",21);Customerc3=newCustomer("ls",19);Customerc4=newCustomer("ls",19);//在TreeSet中添加元素set.add(c1);set.add(c2);set.add(c3);//遍歷集合Iteratorit=set.iterator();while(it.hasNext()){Customerb=(Customer)it.next();System.out.println(b.getName()+"\t"+b.getAge());}}}7.6Map接口Map是一種將鍵對象與值對象進行關(guān)聯(lián)的容器。常用的實現(xiàn):HashMapTreeMapLinkedHashMap例:Mapmap=newHashMap();提供三種Collection視圖SetkeySet()——鍵集Collectionvalues()——值集SetentrySet()——鍵-值對集377.6Map接口38【例7.10】HashMap示例。public
classStudent{privateStringno;privateStringname;private
int
age;privateStringaddress;//getters、setters方法和構(gòu)造方法@OverridepublicStringtoString(){return
"學生學號:"
+this.getNo()+"\t"
+"學生姓名:"
+this.getName()+"\t"
+"學生年齡:"
+this.getAge()+"\t"+"學生地址:"
+this.getAddress();}}39【例7.10】HashMap示例。public
classHashMapTest{public
static
voidmain(String[]args){//定義HashMapMapmap=newHashMap();//定義三個學生對象Studentstu1=newStudent("1001","張明",20,"江蘇徐州");Studentstu2=newStudent("1002","孫旭",19,"江蘇無錫");Studentstu3=newStudent("1003","李東",21,"江蘇南京");//以學號為鍵,學生完整信息為值,保存到map中map.put(stu1.getNo(),stu1);map.put(stu2.getNo(),stu2);map.put(stu3.getNo(),stu3);//containsKey:如果此映射包含指定鍵的映射關(guān)系,則返回trueboolean
isContainsKey=map.containsKey(stu1.getNo());System.out.println("是否包含1001號學生:"
+isContainsKey);//containsValue:如果此映射包含指定值,則返回trueboolean
isContainsValue=map.containsValue(stu2);System.out.println("是否包含1002號學生:"
+isContainsValue);【例7.10】HashMap示例。//獲得指定學號1001的值Studentstu=(Student)map.get("1001");if(stu!=null){System.out.println(stu.getNo()+"\t"+stu.getName());}//entrySet():返回此映射所包含的映射關(guān)系的Set視圖SetentrySet=map.entrySet();Iteratorit=entrySet.iterator();while(it.hasNext()){System.out.println(it.next());}//keySet():返回此映射所包含的鍵的Set視圖SetkeySet=map.keySet();it=keySet.iterator();while(it.hasNext()){System.out.println(it.next());}【例7.10】HashMap示例。//遍歷values()CollectionstuValues=map.values();it=stuValues.iterator();while(it.hasNext()){Students=(Student)it.next();System.out.println(s);}//移除System.out.println("刪除前的map.size="+map.size());map.remove(stu2.getNo());System.out.println("刪除后的map.size="+map.size());//清空System.out.println("清空前的map.size="+map.size());map.clear();System.out.println("清空后的map.size="+map.size());}}【例7.11】TreeMap示例。public
classStudentComparatorimplementsComparator<Student>{@Overridepublic
intcompare(Studentstu1,Studentstu2){if(stu1.getAge()>stu2.getAge()){return1;}else
if(stu1.getAge()<stu2.getAge()){return-1;}else{return0;}}}【例7.11】TreeMap示例。public
classTreeMapTest{public
static
voidmain(String[]args){//定義TreeMapMapmap=newTreeMap(newStudentComparator());//定義三個學
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 陶瓷插芯市場分析及競爭策略分析報告
- 珠光材料市場分析及競爭策略分析報告
- 農(nóng)村安置房合同范本
- 農(nóng)村山地合同范例
- 2004用工合同范本
- 植物保護模擬試題含參考答案
- 維修電工模擬練習題含答案
- 企業(yè)光纖租賃合同范本
- ppp項目股權(quán)合同范例
- 不予退款合同范本
- berg平衡評定量表
- 中央空調(diào)維保方案
- EPC總承包項目財務管理要點
- 一年級下學期開學家長會
- 發(fā)動機飛輪殼加工工藝及其夾具設(shè)計
- 中國控制會議論文模板英文
- 前廳羅盤系統(tǒng)操作細則
- 迅達扶梯9300AE故障代碼
- 二年級下冊數(shù)學課件-第三單元 對稱圖形 ppt(29張) 北京版(2021秋)
- 六十四卦爻象全圖(彩色)(共6頁)
- 《各種各樣的橋》ppt課件
評論
0/150
提交評論