------- android培訓、java培訓、期待與您交流! ----------
16.01 ArrayList存儲字符串并遍歷
ArrayList類概述:底層數據結構是數組,查詢快,增刪慢,線程不安全,效率高
ArrayList類是List 接口的大小可變數組的實現。實現了所有可選列表操作,并允許包括 null在內的所有元素。除了實現 List 接口外,此類還提供一些方法來操作內部用來存儲列表的數組的大小。
例:
1 public class PRactice 2 { 3 public static void main(String[] args) 4 { 5 ArrayList al = new ArrayList(); 6 al.add("hello"); 7 al.add("world"); 8 al.add("java"); 9 10 Iterator it = al.iterator();11 while(it.hasNext())12 {13 String s = (String)it.next();14 System.out.println(s);15 }16 }17 }
16.02 ArrayList存儲自定義對象并遍歷
例:
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 ArrayList al = new ArrayList(); 6 al.add(new Student("小明",23)); 7 al.add(new Student("小紅",15)); 8 al.add(new Student("旺財",16)); 9 al.add(new Student("小強",21));10 al.add(new Student("張三",23));11 12 Iterator it = al.iterator();13 while(it.hasNext())14 {15 Student s = (Student)it.next();16 System.out.println(s.getName()+":"+s.getAge());17 }18 }19 }16.03 Vector的特有功能
Vector類概述:底層數據結構是數組,查詢快,增刪慢,線程安全,效率低
Vector類特有功能
1. public void addElement(E obj):
將指定的組件添加到此向量的末尾,將其大小增加 1。 該方法被add()替代
2. public E elementAt(int index):
返回指定索引處的組件。 該方法被get()替代
3. public Enumeration<E> elements():
返回此向量的組件的枚舉。 該方法被Iterator iterator()替代
補充知識:JDK升級的原因,安全、效率、簡化書寫
16.04 LinkedList的特有功能
LinkedList類概述:底層數據結構是鏈表,查詢慢,增刪快,線程不安全,效率高
LinkedList類特有功能
1. public void addFirst(E e):將指定元素插入此列表的開頭。
2. public void addLast(E e):將指定元素添加到此列表的結尾。
3. public E getFirst():返回此列表的第一個元素。
4. public E getLast():返回此列表的最后一個元素。
5. public E removeFirst():移除并返回此列表的第一個元素。
6. public E removeLast():移除并返回此列表的最后一個元素。
16.05 去除ArrayList集合中的重復字符串元素案例1(兩個集合)
去除ArrayList集合中字符串的重復值(字符串的內容相同)
思路:創建兩個集合,遍歷舊集合獲取每一個元素,查看遍歷到的元素在新集合中是否存在,存在不操作,不存在存入新集合
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 ArrayList al = new ArrayList(); 6 7 al.add("java"); 8 al.add("hello"); 9 al.add("java");10 al.add("world");11 al.add("hello");12 al.add("java");13 //創建新集合14 ArrayList newArray = new ArrayList();15 16 Iterator it = al.iterator();17 while(it.hasNext())18 {19 String s = (String)it.next();20 if(!newArray.contains(s))21 newArray.add(s);22 }23 //遍歷新集合24 Iterator newit = newArray.iterator();25 while(newit.hasNext())26 {27 String s = (String)newit.next();28 System.out.println(s);29 }30 }31 }16.06 去除ArrayList集合中的重復字符串元素案例2(單個集合)
去除ArrayList集合中字符串的重復值(字符串的內容相同),要求不能創建新集合
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 ArrayList al = new ArrayList(); 6 7 al.add("java"); 8 al.add("hello"); 9 al.add("java");10 al.add("world");11 al.add("world");12 al.add("world");13 al.add("hello");14 al.add("java");15 16 for (int i = 0; i < al.size()-1; i++) 17 {18 for (int j = i + 1; j < al.size(); j++) 19 {20 if(al.get(i).equals(al.get(j)))21 {22 al.remove(j); 23 j--;24 }25 }26 }27 28 Iterator it = al.iterator();29 while(it.hasNext())30 {31 String s = (String)it.next();32 System.out.println(s);33 }34 }35 }16.07 去除ArrayList集合中的重復自定義對象元素案例
去除ArrayList集合中自定義對象的重復值(對象的成員變量值都相同)
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 ArrayList al1 = new ArrayList(); 6 7 al1.add(new Student("小明",23)); 8 al1.add(new Student("小明",23)); 9 al1.add(new Student("小紅",15));10 al1.add(new Student("旺財",16));11 al1.add(new Student("小明",18));12 al1.add(new Student("旺財",16));13 al1.add(new Student("小強",21));14 15 ArrayList al2 = new ArrayList();16 //遍歷舊集合17 Iterator it = al1.iterator();18 while(it.hasNext())19 {20 Student s = (Student)it.next();21 //contains()方法底層依賴的是equals()方法22 //Object的equals()方法默認比較的是地址值23 //需重寫equals()方法24 if(!al2.contains(s))25 al2.add(s);26 }27 //遍歷新集合28 Iterator it2 = al2.iterator();29 while(it2.hasNext())30 {31 Student s = (Student)it2.next();32 System.out.println(s.getName()+":"+s.getAge());33 }34 }35 }運行結果:
小明:23小紅:15旺財:16小明:18小強:21
16.08 用LinkedList實現棧結構的集合代碼
LinkedList list = new LinkedList();list.addFirst("hello");list.addFirst("world");list.addFirst("java");Iterator it = list.iterator();while(it.hasNext()){ System.out.println(it.next());}16.09 用LinkedList模擬棧數據結構的集合并測試案例
自己定義一個集合類,底層可以使用LinkedList
public class MyStack { private LinkedList list; public MyStack() { list = new LinkedList(); } //添加方法 public void add(Object obj) { list.addFirst(obj); } //獲取方法 public Object get() { return list.removeFirst(); } //判斷是否為空方法 public boolean isEmpty() { return list.isEmpty(); }}測試類:public class Practice { public static void main(String[] args) { MyStack ms = new MyStack(); ms.add("hello"); ms.add("world"); ms.add("java"); while(!ms.isEmpty()) { System.out.println(ms.get()); } }}16.10 泛型概述和基本使用
例:
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 ArrayList al = new ArrayList(); 6 al.add("hello"); 7 al.add("world"); 8 al.add("java");//String 9 al.add(3);//Integer10 11 Iterator it = al.iterator();12 while(it.hasNext())13 {14 //ClassCastException15 String s = (String)it.next();16 System.out.println(s);17 }18 }19 }上面的代碼會報錯,因為存儲在al集合中的元素有String及Integer類型,在遍歷的時候都當做String類型處理,所以報錯。如果在創建對象的時候就明確元素的數據類型就不會出現問題了,在Java中這種技術成為泛型。
泛型:是一種把類型明確的工作推遲到創建對象或者調用方法的時候才去明確的特殊的類型。參數化類型,把類型當作參數一樣的傳遞。
格式:<數據類型>:此處的數據類型只能是引用類型
例:
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 ArrayList<String> al = new ArrayList<String>(); 6 al.add("hello"); 7 al.add("world"); 8 al.add("java"); 9 10 Iterator<String> it = al.iterator();11 while(it.hasNext())12 {13 String s = it.next();14 System.out.println(s);15 }16 }17 }好處:
1:把運行時期的問題提前到了編譯期間
2:避免了強制類型轉換
3:優化了程序設計,解決了黃色警告線
16.11 ArrayList存儲字符串并遍歷泛型版
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 ArrayList<String> al = new ArrayList<String>(); 6 al.add("hello"); 7 al.add("world"); 8 al.add("java"); 9 10 Iterator<String> it = al.iterator();11 while(it.hasNext())12 {13 String s = it.next();14 System.out.println(s);15 }16 System.out.println("-----");17 for (int i = 0; i < al.size(); i++) 18 {19 String s = al.get(i);20 System.out.println(s);21 }22 }23 }16.12 ArrayList存儲自定義對象并遍歷泛型版
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 //泛型推斷 6 // ArrayList<Student> al = new ArrayList<>(); 7 ArrayList<Student> al = new ArrayList<Student>(); 8 9 al.add(new Student("小明",23));10 al.add(new Student("小紅",15));11 al.add(new Student("旺財",16));12 al.add(new Student("小強",21));13 14 Iterator<Student> it = al.iterator();15 while(it.hasNext())16 {17 Student s = it.next();18 System.out.println(s.getName()+":"+s.getAge());19 }20 }21 }16.13 通過Object轉型問題引入泛型
早期的時候,我們使用Object來代表任意的類型。
向上轉型是沒有任何問題的,但是在向下轉型的時候其實隱含了類型轉換的問題。
也就是說這樣的程序其實并不是安全的。所以Java在JDK5后引入了泛型,提高程序的安全性。
16.14 泛型類的概述及使用
泛型類:把泛型定義在類上
格式:public class 類名<泛型類型1,...>
注意:泛型類型必須是引用類型
例:
1 public class ObjectTool<R> 2 { 3 private R obj; 4 5 public R getObj() 6 { 7 return obj; 8 } 9 10 public void setObj(R obj) 11 {12 this.obj = obj;13 }14 }測試:
ObjectTool<String> ot = new ObjectTool<String>();ot.setObj("hello");System.out.println(ot.getObj());16.15 泛型方法的概述和使用
泛型方法:把泛型定義在方法上
格式:public <泛型類型> 返回類型方法名(泛型類型 ...)
例:
1 //泛型方法,參數類型與類的類型一致,類上的是什么類型,方法的參數類型就是什么類型 2 public void show(R r) 3 { 4 System.out.println(r); 5 } 6 //泛型方法,參數類型與類的類型不一致,類上的類型與方法的參數類型無關 7 //該方法可以接受任意類型 8 public <T> void method(T t) 9 {10 System.out.println(t);11 }測試:
ObjectTool<String> ot1 = new ObjectTool<String>();ObjectTool<Integer> ot2 = new ObjectTool<Integer>();ObjectTool<Boolean> ot3 = new ObjectTool<Boolean>();ot1.show("hello");//類上的是什么類型,方法的參數類型就是什么類型ot2.show(25);ot3.show(true);System.out.println("----");//類上的類型與方法的參數類型無關ot1.method("hello");ot1.method(23);ot1.method(true);16.16 泛型接口的概述和使用
泛型接口:把泛型定義在接口上
格式:public interface 接口名<泛型類型1...>
//泛型接口public interface Inter<T>{ public abstract void show(T t);}//實現類第一種情況:已經知道是什么類型的public class InterImpl implements Inter<String> { @Override public void show(String t) { System.out.println(t); }}//第一種情況測試:public class InterDemo { public static void main(String[] args) { Inter<String> i = new InterImpl(); i.show("hello"); }}//實現類第二種情況:還不知道是什么類型的public class InterImpl<T> implements Inter<T>{ @Override public void show(T t) { System.out.println(t); }}//第二種情況測試:public class InterDemo { public static void main(String[] args) { Inter<String> i1 = new InterImpl<String>(); Inter<Integer> i2 = new InterImpl<Integer>(); i1.show("hello"); i2.show(23); }}16.17 泛型高級之通配符
泛型通配符<?>: 任意類型,如果沒有明確,那么就是Object以及任意的Java類了
? extends E: 向下限定,E及其子類
? super E: 向上限定,E及其父類
例:
public class Practice { public static void main(String[] args) { // 泛型如果明確的寫的時候,前后必須一致 Collection<Object> c1 = new ArrayList<Object>(); // Collection<Object> c2 = new ArrayList<Animal>();//錯誤 // Collection<Object> c3 = new ArrayList<Dog>();//錯誤 // Collection<Object> c4 = new ArrayList<Cat>();//錯誤 // ? 表示任意的類型都是可以的 Collection<?> c5 = new ArrayList<Object>(); Collection<?> c6 = new ArrayList<Animal>(); Collection<?> c7 = new ArrayList<Dog>(); Collection<?> c8 = new ArrayList<Cat>(); // ? extends E:向下限定,E及其子類 // Animal及Animal的子類 // Collection<? extends Animal> c9 = new ArrayList<Object>();//錯誤 Collection<? extends Animal> c10 = new ArrayList<Animal>(); Collection<? extends Animal> c11 = new ArrayList<Dog>(); Collection<? extends Animal> c12 = new ArrayList<Cat>(); // ? super E:向上限定,E及其父類 // Animal及Animal的父類 Collection<? super Animal> c13 = new ArrayList<Object>(); Collection<? super Animal> c14 = new ArrayList<Animal>(); // Collection<? super Animal> c15 = new ArrayList<Dog>();//錯誤 // Collection<? super Animal> c16 = new ArrayList<Cat>();//錯誤 }}class Animal{}class Dog extends Animal{}class Cat extends Animal{}16.18 增強for的概述和使用
JDK5的新特性:自動拆裝箱,泛型,增強for,靜態導入,可變參數,枚舉
增強for概述:簡化數組和Collection集合的遍歷
格式:
for(元素數據類型變量 : 數組或者Collection集合)
{使用變量即可,該變量就是元素}
例:
int[] arr = {11,22,33,44,55};//增強forfor(int x : arr){ System.out.println(x);}好處:簡化遍歷
注意事項:增強for的目標要判斷是否為null
16.19 ArrayList存儲字符串并遍歷增強for版
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 ArrayList<String> al = new ArrayList<String>(); 6 al.add("hello"); 7 al.add("world"); 8 al.add("java"); 9 10 for(String str : al)11 {12 System.out.println(str);13 }14 }15 }16.20 ArrayList存儲自定義對象并遍歷增強for版
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 ArrayList<Student> al = new ArrayList<Student>(); 6 7 al.add(new Student("小明",23)); 8 al.add(new Student("小紅",15)); 9 al.add(new Student("旺財",16));10 al.add(new Student("小強",21));11 12 for(Student s : al)13 {14 System.out.println(s.getName()+":"+s.getAge());15 }16 }17 }16.21 靜態導入的概述和使用
格式:import static 包名….類名.方法名;可以直接導入到方法的級別
例:
1 import static java.lang.Math.abs; 2 import static java.lang.Math.max; 3 import static java.lang.Math.pow; 4 5 public class Practice 6 { 7 public static void main(String[] args) 8 { 9 System.out.println(abs(-10));10 System.out.println(max(20,30));11 System.out.println(pow(2,3));12 }13 }注意事項:
1.方法必須是靜態的
2.如果有多個同名的靜態方法,必須加前綴。由此可見,意義不大,所以一般不用,但是要能看懂。
16.22 可變參數的概述和使用
可變參數概述:定義方法的時候不知道該定義多少個參數
格式:修飾符返回值類型方法名(數據類型… 變量名){}
例:
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 int result1 = sum(11,22,33); 6 int result2 = sum(11,22,33,44); 7 int result3 = sum(11,22,33,44,55); 8 System.out.println(result1); 9 System.out.println(result2);10 System.out.println(result3);11 }12 //可變參數,其實就是一個數組13 public static int sum(int... a)14 {15 int result = 0;16 for(int x : a)17 {18 result += x;19 }20 return result;21 }22 }注意:
1.這里的變量其實是一個數組
2.如果一個方法有可變參數,并且有多個參數,那么,可變參數必須是最后一個
16.23 Arrays工具類的asList()方法的使用(數組轉集合)
Arrays工具類中的一個方法:public static <T> List<T> asList(T... a)
例:
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 String[] strArray = {"hello","world","java"}; 6 List<String> list = Arrays.asList(strArray); 7 for(String s : list) 8 { 9 System.out.println(s);10 }11 System.out.println("-----");12 //可變參數13 List<String> list2 = Arrays.asList("hello","world");14 for(String s : list2)15 {16 System.out.println(s);17 }18 }19 }運行結果:
helloworldjava-----helloWorld
注意事項:雖然可以把數組轉成集合,但是集合的長度不能改變。
16.24 集合嵌套存儲和遍歷元素的案例代碼實現
集合的嵌套遍歷ArrayList嵌套ArrayList
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 // 創建大集合 6 ArrayList<ArrayList<Student>> bigArrayList = new ArrayList<ArrayList<Student>>(); 7 8 //創建第一個集合 9 ArrayList<Student> al1 = new ArrayList();10 al1.add(new Student("小明",23));11 al1.add(new Student("小紅",12));12 al1.add(new Student("小強",26));13 al1.add(new Student("旺財",14));14 //第一個集合添加到大集合15 bigArrayList.add(al1);16 17 //創建第二個集合18 ArrayList<Student> al2 = new ArrayList();19 al1.add(new Student("唐僧",40));20 al1.add(new Student("孫悟空",28));21 al1.add(new Student("豬八戒",29));22 al1.add(new Student("沙僧",27));23 //第二個集合添加到大集合24 bigArrayList.add(al2);25 26 //創建第三個集合27 ArrayList<Student> al3 = new ArrayList();28 al1.add(new Student("宋江",40));29 al1.add(new Student("吳用",35));30 al1.add(new Student("高俅",30));31 al1.add(new Student("李師師",22));32 //第三個集合添加到大集合33 bigArrayList.add(al3);34 35 // 遍歷集合36 for (ArrayList<Student> array : bigArrayList) 37 {38 for (Student s : array) 39 {40 System.out.println(s.getName() + "---" + s.getAge());41 }42 }43 }44 }16.25 產生10個1-20之間的隨機數要求隨機數不能重復案例
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 // 創建產生隨機數的對象 6 Random r = new Random(); 7 8 // 創建一個存儲隨機數的集合。 9 ArrayList<Integer> array = new ArrayList<Integer>();10 11 // 定義一個統計變量。從0開始。12 int count = 0;13 14 // 判斷統計遍歷是否小于1015 while (count < 10) 16 {17 //先產生一個隨機數18 int number = r.nextInt(20) + 1;19 20 //判斷該隨機數在集合中是否存在。21 if(!array.contains(number))22 {23 //如果不存在:就添加,統計變量++。24 array.add(number);25 count++;26 }27 }28 29 //遍歷集合30 for(Integer i : array)31 {32 System.out.println(i);33 }34 }35 }16.26 鍵盤錄入多個數據在控制臺輸出最大值案例
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 // 創建鍵盤錄入數據對象 6 Scanner sc = new Scanner(System.in); 7 8 // 鍵盤錄入多個數據,不知道多少個,所以用集合存儲 9 ArrayList<Integer> array = new ArrayList<Integer>();10 11 // 以0結束只要鍵盤錄入的數據是0,我就不繼續錄入數據了12 //定義一個記錄變量13 int count = 1;14 while (true)15 {16 System.out.println("請輸入第"+(count++)+"個數據");17 int number = sc.nextInt();18 if (number != 0)19 {20 array.add(number);21 } 22 else 23 break;24 }25 26 // 把集合轉成數組27 // public <T> T[] toArray(T[] a)28 Integer[] i = new Integer[array.size()];29 // Integer[] ii = array.toArray(i);30 array.toArray(i);31 System.out.println("排序前的數組是:" + arrayToString(i));32 // 對數組排序33 // public static void sort(Object[] a)34 Arrays.sort(i);35 36 // 獲取該數組中的最大索引的值37 System.out.println("排序后的數組是:" + arrayToString(i) + "/r/n"38 +"最大值是:"+ i[i.length - 1]);39 }40 41 //遍歷數組的方法42 public static String arrayToString(Integer[] i) 43 {44 StringBuilder sb = new StringBuilder();45 46 sb.append("[");47 for (int x = 0; x < i.length; x++) 48 {49 if (x == i.length - 1) 50 {51 sb.append(i[x]);52 } 53 else 54 {55 sb.append(i[x]).append(", ");56 }57 }58 sb.append("]");59 return sb.toString();60 }61 }運行結果:
請輸入第1個數據25請輸入第2個數據15請輸入第3個數據45請輸入第4個數據56請輸入第5個數據58請輸入第6個數據48請輸入第7個數據0排序前的數組是:[25, 15, 45, 56, 58, 48]排序后的數組是:[15, 25, 45, 48, 56, 58]最大值是:58
新聞熱點
疑難解答