java複習第5天---5.1---集合---綜合

java複習第5天---5.1---集合---綜合


目錄




內容

1、Collection

  所有單列集合的根接口,裏面定義了很多集合通用方法,常用方法如下:

修飾符 返回值 方法名 參數 描述
public boolean add E e 向集合中添加元素
public boolean remove Object o 刪除指定的元素o
public void clear 清空集合
public boolean contains Object o 判斷集合是否包含元素 o
public boolean isEmpty 判斷集合是否爲空
public int size 返回集合元素數量
public T[] toArray T[] t 把集合中的元素轉換爲數組
  • 解析:
    • clear:清空集合,不會刪除集合本身
      • 示例:

          package collection.collection;
        
          import java.util.ArrayList;
          import java.util.Collection;
        
          public class TestCollecton1 {
          	public static void main(String[] args) {
          		Collection<Integer> c1= new ArrayList<>();
          		c1.add(1);
          		c1.add(3);
          		c1.add(5);
        
          		System.out.println(c1);
          		c1.clear();
          		System.out.println(c1);
          	}
          }
          測試結果:
          [1, 3, 5]
          []
        

2、Iterator

  Iterator接口也是集合的一部分,Collection和Map用於存儲元素,Iterator用於遍歷集合,因此Iterator被稱爲迭代器。遍歷集合是處理集合時,最常用的操作之一。

  • 常用方法:
修飾符 返回值 方法名 參數 描述
public boolean hasNext 判斷是否有下一個元素
public E next 返回迭代中的下一個元素
default void remove 從底層集合中刪除此迭代器返回的最後一個元素
  • 示例2-1:

      package collection.collection;
    
      import java.util.ArrayList;
      import java.util.Collection;
      import java.util.Iterator;
    
      public class TestIterator1 {
      	public static void main(String[] args) {
      		Collection<String> c1 = new ArrayList<>();
      		c1.add("JAVA");
      		c1.add("Python");
      		c1.add("PHP");
      		c1.add("C++");
    
      		Iterator<String> i1 = c1.iterator();
      		while(i1.hasNext()) {
      			String str = i1.next();
      			System.out.println(str);
      		}
      	}
      }
      測試結果:
      JAVA
      Python
      PHP
      C++
    

2.1、集合遍歷

  常用集合遍歷方式:

  • 普通for循環

    • 適用場景:底層爲數組,可以索引的集合
  • Iterator

    • 適用場景:實現Iterable接口,重寫iterator接口
  • 增強for循環

    • 適用場景:同上,底層代碼通過迭代器實現
  • 示例代碼2.1-1:

      package collection.collection;
    
      import java.util.ArrayList;
      import java.util.Collection;
      import java.util.Iterator;
      import java.util.List;
    
      public class TestIterator1 {
      	public static void main(String[] args) {
      		Collection<String> c1 = new ArrayList<>();
      		c1.add("JAVA");
      		c1.add("Python");
      		c1.add("PHP");
      		c1.add("C++");
    
      		Iterator<String> i1 = c1.iterator();
      		while(i1.hasNext()) {
      			String str = i1.next();
      			System.out.println(str);
      		}
      		System.out.println("=========");
      		List<String> l1  = (ArrayList) c1;
      		for(int i = 0; i < l1.size(); i++) {
      			System.out.println(l1.get(i));
      		}
      		System.out.println("=========");
      		for(String str: l1) {
      			System.out.println(str);
      		}
      	}
      }
      測試結果:
      JAVA
      Python
      PHP
      C++
      =========
      JAVA
      Python
      PHP
      C++
      =========
      JAVA
      Python
      PHP
      C++
    

2、泛型

2.1、概念

  • 泛型:未知的數據類型,當不知道使用什麼數據類型的時候,可以用泛型表示

  • 常用泛型:泛型可以理解爲數據類型常量,一旦賦值,數據類型就確定

    • E:element 元素
    • T:type 類型
  • ArrayList源碼示例:

      public class ArrayList<E> {
      		public E get(int index) {
      			rangeCheck(index);
    
      			return elementData(index);
      	}
      }
    

2.2、類型確定時間

  當泛型對象創建的時候,數據類型確定。

2.3、泛型優點

  不使用泛型的集合:

  • 可以存儲任意類型的元素
  • 類型轉換不安全,容易出現類型轉換錯誤

  使用泛型集合:

  • 避免類型轉換問題,存儲什麼類型,取出的是什麼類型
  • 把運行期異常,提升到編譯期,

2.2、定義泛型類

+格式

	[修飾符] class 類名<代表泛型的變量> {}
  • 示例2.2-1:

      package collection.collection;
    
      public class Generic1<E> {
      	public E name;
    
      	public E getName() {
      		return name;
      	}
    
      	public void setName(E name) {
      		this.name = name;
      	}
    
      	@Override
      	public String toString() {
      		return "Generic1 [name=" + name + "]";
      	}
    
    
      }
      
      package collection.collection;
    
      public class TestGeneric1 {
      	public static void main(String[] args) {
      		Generic1<String> g1 = new Generic1<>();
      		g1.setName("gaogzhen");
      		String name = g1.getName();
    
      		System.out.println(name);
    
      		System.out.println(g1);
      	}
      }
      測試結果:
      gaogzhen
      Generic1 [name=gaogzhen]
    

2.3、定義泛型方法

  • 格式

      [修飾符] 代表泛型的變量 方法名(代表泛型的變量 e) {}
    
  • 示例2.3-1:同上

2.4、定義泛型接口

  • 格式

      [修飾符] interface 接口名<代表泛型的變量> {}
    
  • 示例2.4-1:

      package collection.collection;
    
      public interface GenericInterface1<E> {
      	E get();
      	void set(E e);
      }
      
      package collection.collection;
    
      public class GenericInterfaceImpl<E> implements GenericInterface1<E> {
    
      	public E e;
      	@Override
      	public E get() {
      		// TODO Auto-generated method stub
      		return this.e;
      	}
    
      	@Override
      	public void set(E e) {
      		// TODO Auto-generated method stub
      		this.e = e;
      	}
    
      }
      
      package collection.collection;
    
      public class TestGenericInterfaceImpl {
      	public static void main(String[] args) {
      		GenericInterface1<String> gi = new GenericInterfaceImpl<String>();
      		gi.set("gaogzhen");
      		String str = gi.get();
    
      		System.out.println(str);
      	}
      }
      測試結果:
      gaogzhen
    

3、List

  線性表接口,特點:存儲元素有序,可重複,可索引。常用實現類:ArrayList,LinkedList

  • ArrayList:

    • 特點:底層數組實現,查詢效率高,增刪慢
    • 使用場景:大量查詢業務的集合
  • LinkedList:

    • 特點:底層實現爲鏈表,增刪效率高,查詢慢
    • 適用場景:大量增刪業務的集合
  • 示例3-1:

      package collection.collection;
    
      import java.util.ArrayList;
      import java.util.LinkedList;
      import java.util.List;
    
      public class TestList1 {
      	public static void main(String[] args) {
      		List<String> l1 = new ArrayList<>();
      		l1.add("a");
      		l1.add("b");
      		l1.add("c");
    
      		for(String str: l1) {
      			System.out.println(str);
      		}
      		System.out.println("======");
      		List<String> l2 = new LinkedList<>();
      		l2.add("java");
      		l2.add("c++");
      		l2.add("python");
    
      		for(String str1: l2) {
      			System.out.println(str1);
      		}
    
      	}
      }
      測試結果:
      a
      b
      c
      ======
      java
      c++
      python
    
  • 特有方法:

修飾符 返回值類型 方法名 參數 描述
public E get int index 獲取索引爲index的元素
public E set int index, E e 用指定元素e 替換索引爲index的元素

4、Set

  無序不可重複集合。怎麼保證不重複呢?通過對象的hashcode和equals方法,hashcode需要用到哈希表。哈希表此次不在介紹,可以取看下上一篇博文,或者自行百度。常用的Set的實現類:

  • HashSet:底層哈希表實現,存取順序可能不一致

  • LinkedHashSet:底層鏈表+哈希表,存取順序一致

  • TreeSet:底層樹,排序集合

  • 示例4-1:

      package collection.collection;
    
      import java.util.HashSet;
      import java.util.LinkedHashSet;
      import java.util.Set;
      import java.util.TreeSet;
    
      public class TestSet {
      	public static void main(String[] args) {
      		Set<String> s1 = new HashSet<>();
      		s1.add("a");
      		s1.add("b");
      		s1.add("重地");
      		s1.add("通話");
      		for(String str: s1) {
      			System.out.println(str);
      		}
    
      		System.out.println("======");
    
      		Set<String> s2 = new LinkedHashSet<>();
      		s2.add("a");
      		s2.add("b");
      		s2.add("重地");
      		s2.add("通話");
      		for(String str: s2) {
      			System.out.println(str);
      		}
    
      		System.out.println("======");
    
      		Set<Integer> s3 = new TreeSet<>();
      		s3.add(22);
      		s3.add(424);
      		s3.add(54);
    
    
      		for(int num: s3) {
      			System.out.println(num);
      		}
    
      		System.out.println("======");
      	}
      }
      測試結果:
      a
      b
      重地
      通話
      ======
      a
      b
      重地
      通話
      ======
      22
      54
      424
      ======
    

5、可變參數

  • 格式

      [修飾符] 返回值類型 方法名(普通參數, T...t) {...}等價於
      [修飾符] 返回值類型 方法名(普通參數, T[] t) {...}
    
  • 解析:即可變參數會轉換爲數組處理

  • 規則:

    1. 同一參數列表只能有一個可變參數
    2. 當普通參數和可變參數同時存在時,可變參數必須放在最後
  • 示例5-1:

      package collection.collection;
    
      public class TestVariableParameter {
      	public static void main(String[] args) {
      		int a = 33, b = 44, c = 21; 
      		System.out.println(add(a, b));
      		System.out.println(add(a, b, c));
      	}
    
      	public static int add(int...t) {
      		int sum = 0;
      		for(int i = 0; i < t.length; i++) {
      			sum += t[i];
      		}
    
      		return sum;
      	}
      }
      測試結果:
      77
      98
    

6、Collections工具類

6.1、Comparator和Comparable

  Comparator和Comparable都是實現自定義排序用的,示例代碼見6-4:

  • 常用方法
修飾符 返回值 方法名 參數 描述
static boolean addAll Collection<? super T> c, T… elements 將所有指定的元素添加到指定的集合
static void shuffle List<?> list 使用模式方式隨機排列指定的列表
static <T extends Comparable<? super T>>void sort List list 根據元素的natural ordering 對指定的列表排序
static void sort List list, Comparator<? super T> c 使用指定的排序器對指定列表排序
  • 示例6-1:添加元素

      package collection.collection;
    
      import java.util.ArrayList;
      import java.util.Collections;
      import java.util.List;
    
      public class TestAddAll {
      	public static void main(String[] args) {
      		List<String> l1 = new ArrayList<>();
      
      		// 1、單個添加
      		l1.add("a");
      		l1.add("b");
      		l1.add("c");
      		l1.add("d");
      		System.out.println(l1);
    
      		// 2、一起添加
      		List<String> l2 = new ArrayList<>();
      		Collections.addAll(l2, "a", "b", "c", "d");
      		System.out.println(l2);
      	}
      }
      測試結果:
      [a, b, c, d]
      [a, b, c, d]
    
  • 示例6-2:隨機洗牌

      package collection.collection;
    
      import java.util.ArrayList;
      import java.util.Collections;
    
      public class TestShuffle {
      	public static void main(String[] args) {
      		String[] cardType = {"紅桃", "黑桃" , "梅花", "方片"};
      		String[] cardNumber = {"3", "4", "5", "6", "7", "8","9", "10", "J","Q", "K", "A", "2"};
    
      		ArrayList<String> cards = new ArrayList<>();
      		for(int i = 0; i < cardType.length; i++) {
      			for(int j = 0; j < cardNumber.length; j++) {
      				cards.add(cardType[i] + cardNumber[j]);
      			}
      		}
      		System.out.println("前:"+ cards);
      		Collections.shuffle(cards);
      		System.out.println("後:" + cards);
      	}
      }
      測試結果:
      前:[紅桃3, 紅桃4, 紅桃5, 紅桃6, 紅桃7, 紅桃8, 紅桃9, 紅桃10, 紅桃J, 紅桃Q, 紅桃K, 紅桃A, 紅桃2, 黑桃3, 黑桃4, 黑桃5, 黑桃6, 黑桃7, 黑桃8, 黑桃9, 黑桃10, 黑桃J, 黑桃Q, 黑桃K, 黑桃A, 黑桃2, 梅花3, 梅花4, 梅花5, 梅花6, 梅花7, 梅花8, 梅花9, 梅花10, 梅花J, 梅花Q, 梅花K, 梅花A, 梅花2, 方片3, 方片4, 方片5, 方片6, 方片7, 方片8, 方片9, 方片10, 方片J, 方片Q, 方片K, 方片A, 方片2]
      後:[黑桃A, 方片4, 黑桃8, 紅桃2, 方片Q, 方片2, 梅花5, 方片5, 黑桃10, 梅花4, 梅花8, 梅花10, 梅花A, 梅花2, 黑桃7, 方片7, 紅桃K, 紅桃4, 黑桃J, 梅花J, 紅桃7, 紅桃Q, 方片A, 梅花K, 紅桃9, 方片K, 梅花Q, 黑桃Q, 梅花7, 黑桃4, 黑桃9, 黑桃6, 紅桃10, 紅桃J, 方片6, 黑桃3, 梅花9, 方片9, 梅花6, 方片J, 梅花3, 方片3, 方片8, 紅桃A, 紅桃6, 黑桃K, 紅桃5, 黑桃5, 紅桃3, 黑桃2, 紅桃8, 方片10]
    
  • 示例6-3:默認方式排序

      package collection.collection;
    
      import java.util.ArrayList;
      import java.util.Collections;
    
      public class TestSortDefault {
      	public static void main(String[] args) {
      		ArrayList<Integer> a1 = new ArrayList<>();
      		Collections.addAll(a1, 22, 45, 211, 92, 8);
      		System.out.println("排序前:" + a1);
      		Collections.sort(a1);
      		System.out.println("排序後:" + a1);
      	}
      }
      測試結果:
      排序前:[22, 45, 211, 92, 8]
      排序後:[8, 22, 45, 92, 211]
    
  • 示例6-4:對自定義類進行排序,需要實現Comparable或者Comparator接口

      package collection.collection;
    
      public class Student implements Comparable<Student>{
    
      	public String name;
      	public int age;
    
      	public Student(String name, int age) {
      		this.name = name;
      		this.age = age;
      	}
    
    
      	public String getName() {
      		return name;
      	}
    
    
      	public void setName(String name) {
      		this.name = name;
      	}
    
    
      	public int getAge() {
      		return age;
      	}
    
    
      	public void setAge(int age) {
      		this.age = age;
      	}
    
    
      	@Override
      	public int compareTo(Student o) {
      		// TODO Auto-generated method stub
      		return this.age - o.getAge();
      	}
    
    
      	@Override
      	public String toString() {
      		return "Student [name=" + name + ", age=" + age + "]";
      	}
    
    
    
      }
      
      package collection.collection;
    
      import java.util.ArrayList;
      import java.util.Collections;
      import java.util.Comparator;
    
      public class TestSortCustom {
      	public static void main(String[] args) {
      		ArrayList<Student> a1 = new ArrayList<>();
    
      		a1.add(new Student("張三", 18));
      		a1.add(new Student("李四", 43));
      		a1.add(new Student("王五", 23));
      		a1.add(new Student("唐六", 25));
    
      		System.out.println("排序前:" + a1);
      		//Collections.sort(a1);
    
      		Collections.sort(a1, new Comparator<Student>(){
    
      			@Override
      			public int compare(Student o1, Student o2) {
      				// TODO Auto-generated method stub
      				return o1.getAge() - o2.getAge();
      			}
      		});
      		System.out.println("排序後:" + a1);
    
    
      	}
      }
      測試結果:
      排序前:[Student [name=張三, age=18], Student [name=李四, age=43], Student [name=王五, age=23], Student [name=唐六, age=25]]
      排序後:[Student [name=張三, age=18], Student [name=王五, age=23], Student [name=唐六, age=25], Student [name=李四, age=43]]
    

7、Map

  雙列集合,一個元素k, v)由一對鍵值對組成。

  • k:key 鍵,要求唯一不可重複

  • v: value值,值任意

  • 常用方法:

修飾符 返回值 方法名 參數 描述
public V put K key, V value 將鍵值對(key, value)存入Map中
public V remove Object key 如果key存在,刪除該鍵值對
public V get Object key 獲取key對應的值
public boolean containsKey Object key 判斷集合是否包含key值
public Set keySet 獲取key值的Set集合
public Set<map.Entry<K, V> entrySet 返回map.Entry的Set集合
  • 常用實現類:

    • HashMap:底層哈希表,存取順序可能不一致
    • LinkedHashMap:底層哈希表+鏈表,存取順序一致
    • TreeMap:底層樹,排序Map,元素需要實現Comparable接口
  • 不常用的實現類:

    • HashTable:底層哈希表,線程安全,效率低
  • 綜合示例7-1:

      package collection.collection;
    
      import java.util.HashMap;
      import java.util.Map;
      import java.util.Map.Entry;
      import java.util.Set;
    
      public class TestMap {
      	public static void main(String[] args) {
      		HashMap<Integer, String> hm1 = new HashMap<>();
    
      		hm1.put(1, "JAVA");
      		hm1.put(4, "PHP");
      		hm1.put(3, "Python");
      		hm1.put(2, "C++");
      		System.out.println(hm1);
    
      		System.out.println(hm1.containsKey(2));
    
      		System.out.println(hm1.remove(4));
      		System.out.println(hm1);
    
      		// 1、遍歷方式1
      		Set<Integer> s1 = hm1.keySet();
      		for(int key: s1) {
      			System.out.println(key + "---" + hm1.get(key));
      		}
      		System.out.println("=====");
      		// 2、遍歷方式2
      		Set<Entry<Integer, String>> s2 = hm1.entrySet();
      		for(Entry<Integer, String> kv: s2) {
      			System.out.println(kv.getKey() + "---" + kv.getValue());
      		}
    
    
      	}
      }
    

8、小案例

8.1、統計一個字符串中每個字符出現的次數

	package collection.collection;

	import java.util.HashMap;
	import java.util.Map;

	public class TestMap1 {
		public static void main(String[] args) {
			String str = "djksjo3f30302i0ngi";
			Map<Character, Integer> cal = new HashMap<>();
			char[] chars = str.toCharArray();
			for(char c: chars) {
				if(cal.containsKey(c)) {
					cal.put(c, cal.get(c)+1);
				}else {
					cal.put(c, 1);
				}
			}
			System.out.println(cal);
		}
	}

8.2、模擬鬥地主發牌

  • 分析

    1. 紙牌牌型+紙牌數字 組合成52張牌 + 小王 + 大王
    2. 紙牌隨機分配給3個玩家,最後3張作爲底牌
    3. 展示玩家手中的分到的紙牌和底牌
  • 單列版

      package collection.collection;
    
      import java.util.ArrayList;
      import java.util.Collections;
    
      public class TestShuffle {
      	public static void main(String[] args) {
      		String[] cardType = {"紅桃", "黑桃" , "梅花", "方片"};
      		String[] cardNumber = {"3", "4", "5", "6", "7", "8","9", "10", "J","Q", "K", "A", "2"};
    
      		ArrayList<String> cards = new ArrayList<>();
      		for(int i = 0; i < cardType.length; i++) {
      			for(int j = 0; j < cardNumber.length; j++) {
      				cards.add(cardType[i] + cardNumber[j]);
      			}
      		}
      		cards.add("小王");
      		cards.add("大王");
      		System.out.println("前:"+ cards);
      		Collections.shuffle(cards);
      		System.out.println("後:" + cards);
    
      		ArrayList<String> player1 = new ArrayList<>();
      		ArrayList<String> player2 = new ArrayList<>();
      		ArrayList<String> player3 = new ArrayList<>();
      		ArrayList<String> dipai = new ArrayList<>();
    
      		for(int i = 0; i < cards.size() - 3; i += 3) {
      			player1.add(cards.get(i));
      			player2.add(cards.get(i + 1));
      			player3.add(cards.get(i + 2));
      		}
    
      		dipai.add(cards.get(cards.size() - 3));
      		dipai.add(cards.get(cards.size() - 2));
      		dipai.add(cards.get(cards.size() - 1));
    
      		System.out.println("player1:" + player1);
      		System.out.println("player2:" + player2);
      		System.out.println("player3:" + player3);
      		System.out.println("dipai:" + dipai);
      	}
      }
    
  • 雙列版

      package collection.collection;
    
      import java.util.ArrayList;
      import java.util.Collections;
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
      import java.util.Set;
    
      public class TestShuffle1 {
      	public static void main(String[] args) {
    
      		// 1、組合生成紙牌
      		String[] cardType = {"紅桃", "黑桃", "梅花", "方片"};
      		String[] cardNumber = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
      		int k = 0;
      		Map<Integer, String> cards = new HashMap<>();
      		List<Integer> index = new ArrayList<>();
      		for(String type: cardType) {
      			for(String number: cardNumber) {
      				index.add(k);
      				cards.put(k++, type + number);
      			}
      		}
    
      		index.add(k);
      		cards.put(k++, "小王");
      		index.add(k);
      		cards.put(k++, "大王");
    
      		System.out.println(cards);
      		System.out.println(index);
    
      		// 2、洗牌
      		Collections.shuffle(index);
      		System.out.println(index);
    
      		// 3、發牌
    
      		ArrayList<Integer> player1 = new ArrayList<>();
      		ArrayList<Integer> player2 = new ArrayList<>();
      		ArrayList<Integer> player3 = new ArrayList<>();
      		ArrayList<Integer> dipai = new ArrayList<>();
    
      		for(int i = 0; i < index.size() - 3; i += 3) {
      			player1.add(index.get(i));
      			player2.add(index.get(i + 1));
      			player3.add(index.get(i + 2));
      		}
    
      		dipai.add(index.get(index.size() - 3));
      		dipai.add(index.get(index.size() - 2));
      		dipai.add(index.get(index.size() - 1));
    
    
      		// 4、看牌
      		lookPoker("player1", cards, player1);
      		lookPoker("player2", cards, player2);
      		lookPoker("player3", cards, player3);
      		lookPoker("dipai", cards, dipai);
      	}
    
      	public static void lookPoker(String name, Map<Integer, String> poker, List<Integer> index) {
      		List<String> cards = new ArrayList<>();
      		for(int k: index) {
      			cards.add(poker.get(k));
      		}
      		System.out.println(name +":" + cards);
      	}
      }
    

後記

本項目爲參考某馬視頻開發,相關視頻及配套資料可自行度娘或者聯繫本人。上面爲自己編寫的開發文檔,持續更新。歡迎交流,本人QQ:806797785

前端項目源代碼地址:https://gitee.com/gaogzhen/vue-leyou
    後端JAVA源代碼地址:https://gitee.com/gaogzhen/JAVA

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章