Java集合框架學習筆記及完整源碼案例淺析


一、集合的應用場景

- 無法預測存儲數據的數量

- 需要進行數據的增刪改查

二、集合框架的體系結構

- 接口Collection有三個子接口List(實現類爲ArrayList、LinkedList)、Queue(實現接口爲LinkedList)、Set(HashSet);

- 接口Map的實現類爲HashMap

三、List(列表)

- List是元素有序並且可以重複的集合,稱爲序列

- List的兩個主要實現類是ArrayList和LinkedList

1、ArrayList實現類

- ArrayList底層是由數組實現的

- ArrayList中的元素可以爲null

案例:公告管理

· 需求

- 公告的添加和顯示

- 在指定位置處插入公告

- 刪除公告

- 修改公告

Notice類(javaBean設計思想):

import java.util.Date;

public class Notice {
	private int id;
	private String title;
	private String creator;
	private Date createTime;
	public Notice(int id, String title, String creator, Date createTime) {
		super();
		this.id = id;
		this.title = title;
		this.creator = creator;
		this.createTime = createTime;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getCreator() {
		return creator;
	}
	public void setCreator(String creator) {
		this.creator = creator;
	}
	public Date getCreateTime() {
		return createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
}

NoticeTest類(測試類):

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class NoticeTest {
	public static void main(String[] args) {
		//創建3條公告
		Notice notice1 = new Notice(1001, "關於做好2019年上半年普通話水平測試報名工作的通知", "系統管理員", new Date());
		Notice notice2 = new Notice(1002, "關於參加第九屆全國大學生電子商務“創新、創意和創業”挑戰賽參賽通知", "信息管理員", new Date());
		Notice notice4 = new Notice(1004, "關於2018級學生轉專業考試工作安排的通知", "信息管理員", new Date());
		
		//將公告對象添加到序列
//		List list = new ArrayList();
		List<Notice> list = new ArrayList<Notice>();
		list.add(notice1);
		list.add(notice2);
		list.add(notice4);
		
		//循環打印輸出
		for(int i=0; i<list.size(); i++) {
			System.out.println(i + 1 + " " + ((Notice)(list.get(i))).getTitle());
		}
		System.out.println();
		
		//在指定位置處插入公告
		Notice notice3 = new Notice(1003, "關於2018級學生轉專業考試期間文淵樓封樓的通知", "信息管理員", new Date());
		list.add(2, notice3);
		for(int i=0; i<list.size(); i++) {
			System.out.println(i + 1 + " " + ((Notice)(list.get(i))).getTitle());
		}
		System.out.println();
		
		//刪除公告
		list.remove(0);
//		list.remove(notice1);
		for(int i=0; i<list.size(); i++) {
			System.out.println(i + 1 + " " + ((Notice)(list.get(i))).getTitle());
		}
		System.out.println();
		
		//修改公告
		notice3.setTitle("關於2019級學生轉專業考試期間文淵樓封樓的通知");
//		list.set(2, notice3);  //創建新對象時,才需要
		for(int i=0; i<list.size(); i++) {
			System.out.println(i + 1 + " " + ((Notice)(list.get(i))).getTitle());
		}
		System.out.println();
		
	}
}

2、LinkedList

四、Set集

- Set是元素無序且不可重複的集合,被稱爲集

- HashSet:Set的實現類,稱爲哈希集

- HashSet中只允許一個null元素

- 具有良好的存取和查找性能

案例:狗狗信息管理

· 需求

- 添加和顯示狗狗信息

- 查找某隻狗狗的信息並輸出

- 修改狗狗的信息

- 刪除狗狗信息

Dog類(javaBean設計思想):

public class Dog {
	private String name;   
	private int month;     //狗齡
	private String speces; //品種
	public Dog(String name, int month, String speces) {
		super();
		this.name = name;
		this.month = month;
		this.speces = speces;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getMonth() {
		return month;
	}
	public void setMonth(int month) {
		this.month = month;
	}
	public String getSpeces() {
		return speces;
	}
	public void setSpeces(String speces) {
		this.speces = speces;
	}
	@Override
	public String toString() {
		return "[名字=" + name + ", 狗齡=" + month + ", 品種=" + speces + "]";
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + month;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((speces == null) ? 0 : speces.hashCode());
		return result;
	}
	
	@Override
	public boolean equals(Object obj) {
		//判斷obj是否與當前對象相等
		if(this == obj) {
			return true;
		}
		//判斷obj是否是Dog類的對象
		if(obj.getClass() == Dog.class) {
			Dog dog = (Dog)obj;
			return dog.getName().equals(name) && dog.getMonth()==month && dog.getSpeces().equals(speces);
		}
		return true;
	}	
}

DogTest類(測試類):

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class DogTest {
	public static void main(String[] args) {
		
		Dog maomao = new Dog("毛毛", 5, "金毛");
		Dog qiqi = new Dog("奇奇", 16, "哈士奇");
		
		//將狗狗對象添加入集合
		Set<Dog> set = new HashSet<Dog>();
		set.add(maomao);
		set.add(qiqi);
		
		//顯示狗狗信息
		Iterator<Dog> iterator = set.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}
		System.out.println();
		
		//添加相同狗狗信息
		Dog qiqiRe = new Dog("奇奇", 16, "哈士奇");
		set.add(qiqiRe);
		iterator = set.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}
		System.out.println();
		
		Dog doudou = new Dog("豆豆", 18, "秋田犬");
		set.add(doudou);
		
		//查找doudou對象
		if(set.contains(doudou)) {
			System.out.println("找到了:"+doudou);
		}
		else {
			System.out.println("沒找到");
		}
		System.out.println();
		
		//按名字查找狗狗信息
		boolean flag = false;
		iterator = set.iterator();
		while(iterator.hasNext()) {
			if("奇奇".equals(iterator.next().getName())){
				flag = true;
				break;
			}			
		}
		if(flag) {
			System.out.println("奇奇找到了");
		}
		else {
			System.out.println("奇奇沒找到");
		}
		System.out.println();
		
		//修改狗狗信息
		maomao.setMonth(20);
		
		//刪除指定狗狗信息
//		set.remove(maomao);  //刪除一條
		//刪除一類
//		Set<Dog> set2 = new HashSet<Dog>();
//		iterator = set.iterator();
//		while(iterator.hasNext()) {
//			Dog dog = iterator.next();
//			if(dog.getMonth() < 18){
//				set2.add(dog);
//			}			
//		}
//		set.removeAll(set2);
//		for(Dog dog:set) {
//			System.out.println(dog);
//		}
//		System.out.println();
		//刪除全部
		Boolean flag1 = set.removeAll(set);
		if (flag1) {
			System.out.println("狗狗都沒了");
		}
		else {
			System.out.println("狗狗還在");
		}	
	}
}

五、Map

- Map中的數據是以鍵值對(Key-value)的形式存儲的

- key-value以Entry類型的對象實例存在

- 可以通過key值快速地查找value

- HashMap類是基於哈希表的Map接口的實現

- key值不允許重複

- HashMap中的Entry對象是無序排列的

案例1:類似字典功能的程序

- 將單詞以及單詞的註釋存儲到HashMap中

- 顯示HashMap中的內容

- 查找某個單詞的註釋並顯示

DinctionaryDemo類:

import java.util.*;
import java.util.Map.Entry;

public class DictionaryDemo {

	public static void main(String[] args) {
		Map<String, String> animal = new HashMap<String, String>();
		System.out.println("請輸入三組單詞對應的註釋,並存放到HashMap中");
		Scanner console = new Scanner(System.in);
		//添加數據
		int i=0; 
		while(i<3) {
			System.out.println("請輸入Key值(單詞):");
			String key = console.next();
			System.out.println("請輸入value值(註釋):");
			String value = console.next();
			animal.put(key, value);
			i++;
		}
		System.out.println();
		//打印輸出value值(直接使用迭代器)
		System.out.println("使用迭代器輸出所有的value:");
		Iterator<String> iterator = animal.values().iterator();
		while(iterator.hasNext()) {
			System.out.print(iterator.next()+"  ");
		}
		System.out.println();
		//打印輸出key和value值
		//通過entrySet()
		System.out.println("通過entrySet方法得到key、value:");
		Set<Entry<String, String>> entrySet = animal.entrySet();
		for(Entry<String, String> entry:entrySet) {
			System.out.println(entry.getKey()+"-"+ entry.getValue());
		}
		System.out.println();
		//通過單詞找到註釋並輸出
		//使用keySet方法
		System.out.println("請輸入要查找的單詞:");
		String strSearch = console.next();
		//1、取得keySet
		Set<String> keySet = animal.keySet();
		//2、遍歷keySet	
		for(String key:keySet) {
			if(strSearch.equals(key)) {
				System.out.println("找到了!  " + key+"-" + animal.get(key));
				break;
			}
			else {
				System.out.println("沒找到!");
			}
		}
	}
}

案例2:商品信息管理(練習)

- 使用HashMap對商品進行管理(其中key爲商品編號,value爲商品對象)

- 對HashMap中的商品信息進行增、刪、改、查操作

Goods類(javaBean設計思想):

public class Goods {
	private String id;
	private String name;
	private double price;
	
	public Goods(String id, String name, double price) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String toString() {
		return "商品編號:" + id + ",商品名稱:" + name + ",商品價格:" + price;
	}
}

GoodsTest類(測試類):

import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;

public class GoodsTest {
	public static void main(String[] args) {
		Scanner console = new Scanner(System.in);
		//定義HashMap對象
		Map<String, Goods> goodsMap = new HashMap<String, Goods>();
		System.out.println("****請輸入2條商品信息****");
		int i=0;
		while(i<2) {
			System.out.println("請輸入第"+(i+1)+"條信息");
			System.out.print("-商品編號:"); 
			String goodsId = console.next();	
			//判斷商品編號是否已經存在
			if(goodsMap.containsKey(goodsId)) {
				System.out.println("該商品編號已經存在,請重新輸入:");
				continue;  //i++在語句後,循環變量並不會改變
			}
			System.out.print("-商品名稱:");
			String goodsName = console.next();
			System.out.print("-商品價格:");
			double goodPrice = 0;
			try {
				goodPrice = console.nextDouble();
			} catch (InputMismatchException e) {
				System.out.println("商品價格的格式不正確,請輸入數值型數據!");
				console.next();
				continue; //繼續執行
			}
			
			Goods goods = new Goods(goodsId, goodsName, goodPrice);
			//將商品信息添加到HashMap中
			goodsMap.put(goodsId, goods);
			i++;
		}
		//遍歷Map,輸出商品信息
		System.out.println("商品的全部信息爲:");
		Iterator<Goods> iteratorGoods = goodsMap.values().iterator();
		while(iteratorGoods.hasNext())
		{
			System.out.println(iteratorGoods.next());
		}
        
        //增刪改查操作

	}
}

六、總結

- ArrayList

- HashSet

- HashMap

以上三類的基本操作,具體更多可以查閱參考Java API文檔。

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