全套Java教程_Java基礎入門教程,零基礎小白自學Java必備教程 #011 # 第十一單元 String&ArrayList #
一、本單元知識點概述
(Ⅰ)知識點概述
二、本單元教學目標
(Ⅰ)重點知識目標
1.ArrayList集合的常用方法
2.ArrayList存儲數據和遍曆數據
3.String類的構造方法
4.String類的成員方法
三、本單元知識詳講
11.1 ArrayList類
11.1.1 引入——對象數組
使用學生數組,存儲三個學生對象,程式碼如下:
1 public class Student { 2 private String name; 3 private int age; 4 public Student() { } 5 public Student(String name, int age) { 6 this.name = name; this.age = age; 7 } 8 public String getName() { 9 return name; 10 } 11 public void setName(String name) { 12 this.name = name; 13 } 14 public int getAge() { 15 return age; 16 } 17 public void setAge(int age) { 18 this.age = age; 19 } 20 } 21 22 public class Test01StudentArray { 23 public static void main(String[] args) { 24 //創建學生數組 25 Student[] students = new Student[3]; 26 //創建學生對象 27 Student s1 = new Student("曹操",40); 28 Student s2 = new Student("劉備",35); 29 Student s3 = new Student("孫權",30); 30 //把學生對象作為元素賦值給學生數組 31 students[0] = s1; 32 students[1] = s2; 33 students[2] = s3; 34 //遍歷學生數組 35 for(int x=0; x<students.length; x++) { 36 Student s = students[x]; 37 System.out.println(s.getName()+"‐‐‐"+s.getAge()); 38 } 39 } 40 }
到目前為止,我們想存儲對象數據,選擇的容器,只有對象數組。而數組的長度是固定的,無法適應數據變化的需
求。為了解決這個問題,Java提供了另一個容器 java.util.ArrayList 集合類,讓我們可以更便捷的存儲和操作對象數據。
java.util.ArrayList 是大小可變的數組的實現,存儲在內的數據稱為元素。此類提供一些方法來操作內部存儲的元素。 ArrayList 中可不斷添加元素,其大小也自動增長。
11.1.3 ArrayList使用步驟 ★★★
-
查看類
java.util.ArrayList <E> :該類需要 import導入使後使用。<E> ,表示一種指定的數據類型,叫做泛型。 E ,取自Element(元素)的首字母。在出現 E 的地方,我們使用一種引用數據類型將其替換即可,表示我們將存儲哪種引用類型的元素。程式碼如下:
ArrayList<String>,ArrayList<Student>
public ArrayList() :構造一個內容為空的集合。
ArrayList<String> list = new ArrayList<>();
-
public boolean add(E e) : 將指定的元素添加到此集合的尾部。
參數 E e ,在構造ArrayList對象時, <E> 指定了什麼數據類型,那麼 add(E e) 方法中,只能添加什麼數據
類型的對象。
1 public class Test02StudentArrayList { 2 public static void main(String[] args) { 3 //創建學生數組 4 ArrayList<String> list = new ArrayList<>(); 5 //創建學生對象 6 String s1 = "曹操"; 7 String s2 = "劉備"; 8 String s3 = "孫權"; 9 //列印學生ArrayList集合 10 System.out.println(list); 11 //把學生對象作為元素添加到集合 12 list.add(s1); 13 list.add(s2); 14 list.add(s3); 15 //列印學生ArrayList集合 16 System.out.println(list); 17 } 18 }
11.1.4 常用方法和遍歷★★★★★
對於元素的操作,基本體現在——增、刪、查。常用的方法有:
-
public boolean add(E e) :將指定的元素添加到此集合的尾部。
-
public E remove(int index) :移除此集合中指定位置上的元素。返回被刪除的元素。
-
public E get(int index) :返回此集合中指定位置上的元素。返回獲取的元素。
-
public int size() :返回此集合中的元素數。遍歷集合時,可以控制索引範圍,防止越界。
這些都是最基本的方法,操作非常簡單,程式碼如下:
1 public class Demo01ArrayListMethod { 2 public static void main(String[] args) { 3 //創建集合對象 4 ArrayList<String> list = new ArrayList<String>(); 5 //添加元素 6 list.add("hello"); 7 list.add("world"); 8 list.add("java"); 9 //public E get(int index):返回指定索引處的元素 10 System.out.println("get:"+list.get(0)); 11 System.out.println("get:"+list.get(1)); 12 System.out.println("get:"+list.get(2)); 13 //public int size():返回集合中的元素的個數 14 System.out.println("size:"+list.size()); 15 //public E remove(int index):刪除指定索引處的元素,返回被刪除的元素 16 System.out.println("remove:"+list.remove(0)); 17 //遍歷輸出 for(int i = 0; i < list.size(); i++){ 18 System.out.println(list.get(i)); 19 } 20 } 21 } 22
11.1.5 如何存儲基本數據類型 ★★★★
ArrayList對象不能存儲基本類型,只能存儲引用類型的數據。但是存儲基本數據類型對應的包裝類型是可以的。所以,想要存儲基本類型數據, <> 中的數據類型,必須轉換後才能編寫,轉換寫法如下:
基本類型包裝類 | |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean |
我們發現,只有 Integer 和 Character 需要特殊記憶,其他基本類型只是首字母大寫即可。那麼存儲基本類型數 據,程式碼如下:
1 public class Demo02ArrayListMethod { 2 public static void main(String[] args) { 3 ArrayList<Integer> list = new ArrayList<Integer>(); 4 list.add(1); 5 list.add(2); 6 list.add(3); 7 list.add(4); 8 System.out.println(list); 9 } 10 }
11.1.6 ArrayList
-
數值添加到集合
生成6個1~33之間的隨機整數,添加到集合,並遍歷
1 public class Test01ArrayList { 2 public static void main(String[] args) { 3 // 創建Random 對象 4 Random random = new Random(); 5 // 創建ArrayList 對象 6 ArrayList<Integer> list = new ArrayList<>(); 7 // 添加隨機數到集合 8 for (int i = 0; i < 6; i++) { 9 int r = random.nextInt(33) + 1; 10 list.add(r); 11 } 12 // 遍歷集合輸出 13 for (int i = 0; i < list.size(); i++) { 14 System.out.println(list.get(i)); 15 } 16 } 17 }
1 public class Test02ArrayList { 2 public static void main(String[] args) { 3 //創建集合對象 4 ArrayList<Student> list = new ArrayList<Student>(); 5 //創建學生對象 6 Student s1 = new Student("趙麗穎",18); 7 Student s2 = new Student("唐嫣",20); 8 Student s3 = new Student("景甜",25); 9 Student s4 = new Student("柳岩",19); 10 //把學生對象作為元素添加到集合中 11 list.add(s1); 12 list.add(s2); 13 list.add(s3); 14 list.add(s4); 15 //遍歷集合 16 for(int x = 0; x < list.size(); x++) { 17 Student s = list.get(x); 18 System.out.println(s.getName()+"‐‐‐"+s.getAge()); 19 } 20 } 21 }
1 public class Test03ArrayList { 2 public static void main(String[] args) { 3 // 創建集合對象 4 ArrayList<String> list = new ArrayList<String>(); 5 // 添加字元串到集合中 6 list.add("張三丰"); 7 list.add("宋遠橋"); 8 list.add("張無忌"); 9 list.add("殷梨亭"); 10 // 調用方法 11 printArrayList(list); 12 } 13 14 public static void printArrayList(ArrayList<String> list) { 15 // 拼接左括弧 16 System.out.print("{"); 17 // 遍歷集合 18 for (int i = 0; i < list.size(); i++) { 19 // 獲取元素 20 String s = list.get(i); 21 // 拼接@符號 22 if (i != list.size() ‐ 1) { 23 System.out.print(s + "@"); 24 } else { 25 // 拼接右括弧 26 System.out.print(s + "}"); 27 } 28 } 29 } 30 }
1 public class Test04ArrayList { 2 public static void main(String[] args) { 3 // 創建Random 對象 4 Random random = new Random(); 5 // 創建ArrayList 對象 6 ArrayList<Integer> list = new ArrayList<>(); 7 // 添加隨機數到集合 8 for (int i = 0; i < 20; i++) { 9 int r = random.nextInt(1000) + 1; 10 list.add(r); 11 } 12 // 調用偶數集合的方法 13 ArrayList<Integer> arrayList = getArrayList(list); 14 System.out.println(arrayList); 15 } 16 17 public static ArrayList<Integer> getArrayList(ArrayList<Integer> list) { 18 // 創建小集合,來保存偶數 19 ArrayList<Integer> smallList = new ArrayList<>(); 20 // 遍歷list 21 for (int i = 0; i < list.size(); i++) { 22 // 獲取元素 23 Integer num = list.get(i); 24 // 判斷為偶數,添加到小集合中 25 if (num % 2 == 0){ 26 smallList.add(num); 27 } 28 } 29 // 返回小集合 30 return smallList; 31 } 32 }
1 public class Test04ArrayList { 2 public static void main(String[] args) { 3 // 創建Random 對象 4 Random random = new Random(); 5 // 創建ArrayList 對象 6 ArrayList<Integer> list = new ArrayList<>(); 7 // 添加隨機數到集合 8 for (int i = 0; i < 20; i++) { 9 int r = random.nextInt(1000) + 1; 10 list.add(r); 11 } 12 // 調用偶數集合的方法 13 ArrayList<Integer> arrayList = getArrayList(list); 14 System.out.println(arrayList); 15 } 16 17 public static ArrayList<Integer> getArrayList(ArrayList<Integer> list) { 18 // 創建小集合,來保存偶數 19 ArrayList<Integer> smallList = new ArrayList<>(); 20 // 遍歷list 21 for (int i = 0; i < list.size(); i++) { 22 // 獲取元素 23 Integer num = list.get(i); 24 // 判斷為偶數,添加到小集合中 25 if (num % 2 == 0){ 26 smallList.add(num); 27 } 28 } 29 // 返回小集合 30 return smallList; 31 } 32 }
11.2 String類
11.2.1 String的概述★★★
概述
java.lang.String 類代表字元串。Java程式中所有的字元串文字(例如 “abc” )都可以被看作是實現此類的實例。類 String中包括用於檢查各個字元串的方法,比如用於比較字元串,搜索字元串,提取子字元串以及創建具有翻譯為大寫或小寫的所有字元的字元串的副本。
1.字元串不變:字元串的值在創建後不能被更改。
1 String s1 = "abc"; 2 s1 += "d"; 3 System.out.println(s1);// "abcd" 4 // 記憶體中有"abc","abcd"兩個對象,s1從指向"abc",改變指向,指向了"abcd"。
2.因為String對象是不可變的,所以它們可以被共享。
1 String s1 = "abc"; 2 String s2 = "abc"; 3 // 記憶體中只有一個"abc"對象被創建,同時被s1和s2共享。
例如: String str = "abc"; 相當於: char data[] = {'a', 'b', 'c'}; String str = new String(data); // String底層是靠字元數組實現的。
11.2.2 使用步驟★★★
-
查看類
-
-
查看構造方法
-
java.lang.String :此類不需要導入。 查看構造方法**
-
public String() :初始化新創建的 String對象,以使其表示空字元序列。
-
public String(char[] value) :通過當前參數中的字元數組來構造新的String。
-
public String(byte[] bytes) :通過使用平台的默認字符集解碼當前參數中的位元組數組來構造新的 String.
-
構造舉例,程式碼如下:
-
// 無參構造 String str = new String(); // 通過字元數組構造 char chars[] = {'a', 'b', 'c'}; String str2 = new String(chars); // 通過位元組數組構造 byte bytes[] = { 97, 98, 99 }; String str3 = new String(bytes);
11.2.3 常用方法 ★★★
判斷功能的方法
-
public boolean equals (Object anObject) :將此字元串與指定對象進行比較。
-
public boolean equalsIgnoreCase (String anotherString) :將此字元串與指定對象進行比較,忽略大小
寫。
1 public class String_Demo01 { 2 public static void main(String[] args) { 3 // 創建字元串對象 4 String s1 = "hello"; 5 String s2 = "hello"; 6 String s3 = "HELLO"; 7 // boolean equals(Object obj):比較字元串的內容是否相同 8 System.out.println(s1.equals(s2));// true 9 System.out.println(s1.equals(s3)); // false 10 System.out.println("‐‐‐‐‐‐‐‐‐‐‐"); 11 //boolean equalsIgnoreCase(String str):比較字元串的內容是否相同,忽略大小寫 12 System.out.println(s1.equalsIgnoreCase(s2)); // true 13 System.out.println(s1.equalsIgnoreCase(s3)); // true 14 System.out.println("‐‐‐‐‐‐‐‐‐‐‐"); 15 } 16 }
Object 是」 對象」的意思,也是一種引用類型。作為參數類型,表示任意對象都可以傳遞到方法中。
獲取功能的方法
-
public int length () :返回此字元串的長度。
-
public String concat (String str) :將指定的字元串連接到該字元串的末尾。
-
-
public int indexOf (String str) :返回指定子字元串第一次出現在該字元串內的索引。
-
public String substring (int beginIndex) :返回一個子字元串,從beginIndex開始截取字元串到字元串結尾。
-
public String substring (int beginIndex, int endIndex) :返回一個子字元串,從beginIndex到 endIndex截取字元串。含beginIndex,不含endIndex。
方法演示,程式碼如下:
1 public class String_Demo02 { 2 public static void main(String[] args) { 3 //創建字元串對象 4 String s = "helloworld"; 5 // int length():獲取字元串的長度,其實也就是字元個數 6 System.out.println(s.length()); 7 System.out.println("‐‐‐‐‐‐‐‐"); 8 // String concat (String str):將將指定的字元串連接到該字元串的末尾. 9 String s = "helloworld"; 10 String s2 = s.concat("**hello jiyun"); 11 System.out.println(s2);// helloworld**hello jiyun 12 // char charAt(int index):獲取指定索引處的字元 13 System.out.println(s.charAt(0)); 14 System.out.println(s.charAt(1)); 15 System.out.println("‐‐‐‐‐‐‐‐"); 16 // int indexOf(String str):獲取str在字元串對象中第一次出現的索引,沒有返回‐1 17 System.out.println(s.indexOf("l")); 18 System.out.println(s.indexOf("owo")); 19 System.out.println(s.indexOf("ak")); 20 System.out.println("‐‐‐‐‐‐‐‐"); 21 // String substring(int start):從start開始截取字元串到字元串結尾 22 System.out.println(s.substring(0)); 23 System.out.println(s.substring(5)); 24 System.out.println("‐‐‐‐‐‐‐‐"); 25 // String substring(int start,int end):從start到end截取字元串。含start,不含end。 26 System.out.println(s.substring(0, s.length())); 27 System.out.println(s.substring(3,8)); 28 } 29 }
轉換功能的方法
-
public char[] toCharArray () :將此字元串轉換為新的字元數組。
-
public byte[] getBytes () :使用平台的默認字符集將該 String編碼轉換為新的位元組數組。
-
public String replace (CharSequence target, CharSequence replacement) :將與target匹配的字元串使
用replacement字元串替換。
1 public class String_Demo03 { 2 public static void main(String[] args) { 3 //創建字元串對象 4 String s = "abcde"; 5 // char[] toCharArray():把字元串轉換為字元數組 6 char[] chs = s.toCharArray(); 7 for(int x = 0; x < chs.length; x++) { 8 System.out.println(chs[x]); 9 } 10 System.out.println("‐‐‐‐‐‐‐‐‐‐‐"); 11 // byte[] getBytes ():把字元串轉換為位元組數組 12 byte[] bytes = s.getBytes(); 13 for(int x = 0; x < bytes.length; x++) { 14 System.out.println(bytes[x]); 15 } 16 System.out.println("‐‐‐‐‐‐‐‐‐‐‐"); 17 // 替換字母it為大寫IT 18 String str = "jiyun itedo"; 19 String replace = str.replace("it", "IT"); 20 System.out.println(replace); 21 // jiyun ITedo 22 System.out.println("‐‐‐‐‐‐‐‐‐‐‐"); 23 } 24 }
CharSequence 是一個介面,也是一種引用類型。作為參數類型,可以把String對象傳遞到方法中。
分割功能的方法
方法演示,程式碼如下:
1 public class String_Demo03 { 2 public static void main(String[] args) { 3 //創建字元串對象 4 String s = "aa|bb|cc"; 5 String[] strArray = s.split("|"); 6 // ["aa","bb","cc"] 7 for(int x = 0; x < strArray.length; x++) { 8 System.out.println(strArray[x]); 9 // aa bb cc 10 } 11 } 12 }
11.2.4 String類的練習 ★★★★
拼接字元串
1 public class StringTest1 { 2 public static void main(String[] args) { 3 //定義一個int類型的數組 4 int[] arr = {1, 2, 3}; 5 //調用方法 6 String s = arrayToString(arr); 7 //輸出結果 8 System.out.println("s:" + s); 9 } 10 /* 11 * 寫方法實現把數組中的元素按照指定的格式拼接成一個字元串 12 * 兩個明確: 13 * 返回值類型:String 14 * 參數列表:int[] arr 15 */ 16 public static String arrayToString(int[] arr) { 17 // 創建字元串s 18 String s = new String("["); 19 // 遍曆數組,並拼接字元串 20 for (int x = 0; x < arr.length; x++) { 21 if (x == arr.length ‐ 1) { 22 s = s.concat(arr[x] + "]"); 23 } else { 24 s = s.concat(arr[x] + "#"); 25 } 26 } 27 return s; 28 } 29 }
鍵盤錄入一個字元串,統計字元串中大小寫字母及數字字元個數
1 public class StringTest2 { 2 public static void main(String[] args) { 3 //鍵盤錄入一個字元串數據 4 Scanner sc = new Scanner(System.in); 5 System.out.println("請輸入一個字元串數據:"); 6 String s = sc.nextLine(); 7 //定義三個統計變數,初始化值都是0 8 int bigCount = 0; 9 int smallCount = 0; 10 int numberCount = 0; 11 //遍歷字元串,得到每一個字元 12 for(int x=0; x<s.length(); x++) { 13 char ch = s.charAt(x); 14 //拿字元進行判斷 15 if(ch>='A'&&ch<='Z') { 16 bigCount++; 17 }else if(ch>='a'&&ch<='z') { 18 smallCount++; 19 }else if(ch>='0'&&ch<='9') { 20 numberCount++; 21 }else { 22 System.out.println("該字元"+ch+"非法"); 23 } 24 } 25 //輸出結果 26 System.out.println("大寫字元:"+bigCount+"個"); 27 System.out.println("小寫字元:"+smallCount+"個"); 28 System.out.println("數字字元:"+numberCount+"個"); 29 } 30 }