主頁 > 後端開發 > 容器的介紹、實作及使用

容器的介紹、實作及使用

2020-10-02 17:35:52 後端開發

泛型:

陣列就是一種容器,可以在其中放置物件或基本型別資料.

陣列的優勢:是一種簡單的線性序列,可以快速地訪問陣列元素,效率高.如果從效率和型別檢查的角度講,
陣列是最好的.


陣列的劣勢:不靈活.容量需要事先定義好,不能隨著需求的變化而擴容.

以下是容器的介面層次結構圖:
-----------------------------------------
                     Collection        Map
                         ^              ^
                        / \             |                          
                       /   \         HashMap
                      /     \
                    Set    List
                    /         |
                   /         / \
             HashSet        /   \
                     ArrayList  LinkedList       

-----------------------------------------

泛型是JDK1.5以后增加的,它可以幫助我們建立型別安全的集合.在使用了泛型的集合中,遍歷時不必進行強制型別轉換.
JDK提供了支持泛型的編譯器,將運行時的型別檢查提前到了編譯時執行,提高了代碼可讀性和安全性.

泛型的本質就是“資料型別的引數化”. 我們可以把“泛型”理解為資料型別的一個占位符(形式引數),即告訴編譯器,
在呼叫泛型時必須傳入實際型別.

-----------------------------------------

自定義泛型:

我們可以在類的宣告處增加泛型串列,如:<T,E,V>.

此處,字符可以是任何識別符號,一般采用這3個字母.

----------------------------------------
public class TestGeneric {
	public static void main(String[] args) {
		MyCollection<String> mm = new MyCollection<String>();
		mm.set("字串", 0);
		String str = mm.get(0);
	}
}

class MyCollection<E>{
	Object[] obj = new Object[6];
	
	public void set(E e,int index) {
		obj[index] = e;
	}
	
	public E get(int index) {
		return (E)obj[index];
	}
}
----------------------------------------

容器中使用泛型:

容器相關類都定義了泛型,我們在開發和作業中,在使用容器類時都要使用泛型.這樣,在容器的存盤資料、
讀取資料時都避免了大量的型別判斷,非常便捷.
----------------------------------
public class Test {
    public static void main(String[] args) {
        // 以下代碼中List、Set、Map、Iterator都是與容器相關的介面;
        List<String> list = new ArrayList<String>();
        Set<Man> mans = new HashSet<Man>();
        Map<Integer, Man> maps = new HashMap<Integer, Man>();
        Iterator<Man> iterator = mans.iterator();
    }
}
-----------------------------------
Collection、List、Set、Map、Iterator介面都定義了泛型.

Collection介面:

Collection 表示一組物件.Collection介面的兩個子介面是List、Set介面.
-----------------------------------
         方法                              說明
boolean add(Object element)          增加元素到容器中
boolean remove(Object element)       從容器中移除元素
boolean contains(Object element)     容器中是否包含該元素
int size()                           容器中元素的數量
boolean isEmpty()                    容器是否為空
void clear()                         清空容器中所有元素
Iterator iterator()                  獲得迭代器,用于遍歷所有元素
boolean containsAll(Collection c)    本容器是否包含c容器中的所有元素
boolean addAll(Collection c)         將容器c中所有元素增加到本容器
boolean removeAll(Collection c)      移除本容器和容器c中都包含的元素
boolean retainAll(Collection c)      取本容器和容器c中都包含的元素,移除非交集元素.
Object[] toArray()                   轉化成Object陣列

-----------------------------------
由于List、Set是Collection的子介面,意味著所有List、Set的實作類都有上面的方法.

List特點和常用方法:

List是有序、可重復的容器.

有序:List中每個元素都有索引標記.可以根據元素的索引標記(在List中的位置)訪問元素,從而精確控制這些元素.

可重復:List允許加入重復的元素.更確切地講,List通常允許滿足 e1.equals(e2) 的元素重復加入容器.

除了Collection介面中的方法,List多了一些跟順序(索引)有關的方法:
-----------------------------------

方法	                                           說明
void add(int index,Object element)	    在指定位置插入元素,以前元素全部后移一位
Object set(int index,Object element)	修改指定位置的元素
Object get(int index)	                回傳指定位置的元素
Object remove(intindex)	                洗掉指定位置的元素,后面元素全部前移一位
int indexOf(Object o)	                回傳第一個匹配元素的索引,如果沒有該元素,回傳-1.
int lastIndexOf(Object o)	            回傳最后一個匹配元素的索引,如果沒有該元素,回傳-1.

-----------------------------------

List介面常用的實作類有3個:ArrayList、LinkedList和Vector.

-----------------------------------
例:

import java.util.ArrayList;
import java.util.Collection;

public class TestList {
	public static void main(String[] args) {
		Collection<String> c = new ArrayList<>();
		
		System.out.println(c.size());
		System.out.println(c.isEmpty()); // 判斷容器中是否為空
		
		// 向容器中添加元素
		c.add("dog");
		c.add("cat");
		
		System.out.println(c.contains("dog")); // 判斷容器中是否包含此元素
		
		System.out.println(c);
		System.out.println(c.size()); // 容器中元素的個數
		
		Object[] obj = c.toArray(); // 將容器轉換成物件陣列
		System.out.println(obj);
		
		c.remove("cat");  // 從容器中移除某元素
		System.out.println(c);
		
		c.clear();  // 移除容器中的所有元素
		System.out.println(c);
	}
}
-----------------------------------

兩個List之間的元素操作:

import java.util.*;

public class TestList02 {
	public static void main(String[] args) {
		List<String> c1 = new ArrayList<>();
		
		c1.add("aaa");
		c1.add("bbb");
		c1.add("ccc");
		
		List<String> c2 = new ArrayList<>();
		c2.add("bbb");
		c2.add("ddd");
		c2.add("eee");
		
		System.out.println("List01:"+c1);
		System.out.println("List02:"+c2);
		
		 c1.addAll(c2); // 將c2中所有元素都加入到c1中
		 boolean b = c1.containsAll(c2); // 判斷c1中是否包含c2的所有元素
		 c1.removeAll(c2);  // 將c2中在c1中出現的所有元素都洗掉(洗掉交集元素)
		 c1.retainAll(c2);  // 取交集
		
		System.out.println("List01:"+c1);
		System.out.print(b);
	}
}

List中操作索引的常用方法:

import java.util.*;

public class Test03 {
	
	public static void main(String[] args) {
		
		List<String> c = new ArrayList<>();
		
		c.add("A");
		c.add("B");
		c.add("C");
		c.add("D");
		
		System.out.println(c);
		
		c.add(1, "X"); // 在指定位置插入元素
		System.out.println(c);
		
		c.remove(2);  // 洗掉指定位置的元素
		System.out.println(c);
		
		c.set(2,"MMM"); // 將指定位置設定為指定元素
		System.out.println(c);
		
		System.out.println(c.get(1)); // 獲取指定索引位置的元素
		
		c.add("D");
		c.add("C");
		c.add("B");
		c.add("A");
		
		System.out.println(c);
		
		System.out.println(c.indexOf("D")); // 獲取元素第一次出現的位置索引,沒有則回傳-1

		System.out.println(c.lastIndexOf("A")); // 獲取元素最后一次出現的位置索引
	}
}

手動實作容器ArrayList:

ArrayList底層是用陣列實作的存盤. 特點:查詢效率高,增刪效率低,執行緒不安全.我們一般使用它.

--------------------------------


public class MyCollection<E> {
	
	private Object[] elementData;
	private int size;
	
	private static final int DEFAULT_CAPACITY = 10;
	
	public MyCollection() {
		elementData = new Object[DEFAULT_CAPACITY];
	}
	
	public int size() {
		return size;
	}
	
	public boolean isEmpty() {
		if(size==0) {
			return true;
		}
		return false;
	}
	
	public MyCollection(int capacity) {
		if(capacity < 0) {
			throw new RuntimeException("索引不能為負數");
		}else if(capacity == 0){
			elementData = new Object[DEFAULT_CAPACITY];
		}
		elementData = new Object[capacity];
	}
	
	// 添加元素
	public void add(E element) {
		
		if(size==elementData.length) {
			// 對容器擴容
			Object[] newArray = new Object[elementData.length+(elementData.length >> 1)]; 
			System.arraycopy(elementData, 0, newArray, 0, elementData.length);
			this.elementData = newArray;
		}
		
		elementData[size++] = element;
	}
	
	// 重寫toString方法,列印所有元素
	@Override
	public String toString() {
		
		StringBuilder str = new StringBuilder();
		
		str.append("[");
		for(int i=0;i<size;i++) {
			str.append(elementData[i]+", ");
		}
		
		str.setCharAt(str.length()-2, ']');
		str.delete(str.length()-1, str.length());
		
		return str.toString();
	}
	
	// 獲取指定位置元素
	public E get(int index) {
		
		checkRange(index);
		return (E)elementData[index];
	}
	
	// 設定指定位置的元素
	public void set(int index, E element) {
		
		checkRange(index);
		
		elementData[index] = element;
		
	}
	
	// 檢查是否越界
	public void checkRange(int index) {
		
		if(index<0||index>size-1) {
			throw new RuntimeException("索引錯誤");
		}
		
	}
	
	// 洗掉指定元素
	public void remove(E element) {
		
		for(int i=0;i<size;i++) {
			
			if(elementData[i].equals(element)) {
				remove(i);
			}	
		}
	}
	
	public void remove(int index) {
		checkRange(index);
		if(index!=size-1) {
			// 移動的長度
			int moveLen = size-index-1;
			System.arraycopy(elementData, index+1, elementData, index, moveLen);
		}
		
		elementData[--size] = null; // 最后位置的索引為size-1,所以應該先減一
	}
	
	public static void main(String[] args) {
		
		MyCollection<String> arr = new MyCollection<>(20);
		
		for(int i=0;i<50;i++) {
			arr.add("dog:"+i);
		}
		
		System.out.println(arr);
		
		arr.set(10, "cat");
		String s = arr.get(10);
		System.out.println(s);
		System.out.println(arr);
		
		arr.remove(3);
		
		System.out.println(arr);
		
		arr.remove("dog:8");
		System.out.println(arr);
		
		System.out.println(arr.size());
		
		System.out.println(arr.isEmpty());
	}
}

手動實作容器LinkedList:

LinkedList底層用雙向鏈表實作的存盤.特點:查詢效率低,增刪效率高,執行緒不安全.

雙向鏈表也叫雙鏈表,是鏈表的一種,它的每個資料節點中都有兩個指標,分別指向前一個節點和后一個節點. 
所以,從雙向鏈表中的任意一個節點開始,都可以很方便地找到所有節點.

------------------------------------

public class Node {
	
	Node previous;
	Node next;
	Object element;
	
	public Node(Node previous, Node next, Object element) {
		super();
		this.previous = previous;
		this.next = next;
		this.element = element;
	}

	public Node(Object element) {
		super();
		this.element = element;
	}
}

------------------------------------

public class LinkedList<E>{
	
	private Node first;
	private Node last;
	
	private static int size;
	
	// 在指定位置插入元素
	public void add(int index,E element) {
		
		Node temp = getNode(index);
		Node newNode = new Node(element);
		
		if(temp!=null) {
			
			Node up = temp.previous;
			Node down = temp.next;
			if(up!=null) {
				up.next = newNode;
				newNode.previous = up;
			}else {
				first = newNode;
			}
			
			newNode.next = temp;
			temp.previous = newNode;
		}
		size++;
	}
	
	// 洗掉指定位置元素
	public void remove(int index) {
		
		Node temp = getNode(index);
		Node down;
		Node up;
		if(temp!=null) {
			down = temp.next;
			up = temp.previous;
			
			if(up!=null) {
				up.next = down;
			}else {
				first = down;
			}
			
			if(down!=null) {
				down.previous = up;
			}else {
				last=up;
			}
		}
		
		
		
		size--;
	}
	
	// 獲取指定位置節點元素的值
	public E get(int index) {
		
		Node temp = getNode(index);
		
		return temp!=null ? (E)temp.element:null;
	}
	
	private void checkRange(int index) {
		if(index<0||index>size-1) {
			throw new RuntimeException("索引數字不合法:"+index);
		}
	}
	
	// 獲取指定索引位置節點
	private Node getNode(int index) {
		
		checkRange(index);
		
		Node temp = null;
		
		if(index<(size>>1)) {
			temp = first;
			
			for(int i=0;i<index;i++) {
				temp = temp.next;
			}
		}else {
			
			temp = last;
			for(int i=size-1;i>index;i--) {
				temp = temp.previous;
			}	
		}
		return temp;
	}
	
	
	@Override
	public String toString() {
		
		StringBuilder str = new StringBuilder("[");
		Node temp = first;
		while(temp!=null) {
			
			str.append(temp.element+", ");
			temp = temp.next;
		}
		
		str.setCharAt(str.length()-2, ']');
		str.delete(str.length()-1, str.length());
		System.out.println(str);
		
		return "";
	}
	
	// 增加節點
	public void add(E element) {
		
		Node node = new Node(element);
		
		if(first==null) {
			
			first = node;
			last = node;
			
		}else {
			
			node.previous = last;
			node.next = null;
			
			last.next = node;
			last = node;
		}
		
		size++;
	}
	
	public static int size() {
		return size;
	}
	
	public static void main(String[] args) {
		
		LinkedList<String> list = new LinkedList<>();
		
		list.add("a");
		list.add("b");
		list.add("c");
		list.add("a");
		list.add("b");
		list.add("c");
		
		list.toString();
		System.out.println(list.get(2));
		
		list.remove(5);
		list.toString();
		
		list.add(0, "123");
		list.toString();
		list.add(2,"222");
		list.toString();
		list.add(list.size()-1,"00");
		list.toString();
		
	}
}

Vector向量:

Vector底層是用陣列實作的List,相關的方法都加了同步檢查,因此“執行緒安全,效率低”.很多方法增加了synchronized同步標記.

1. 涉及執行緒安全時,用Vector.

2. 不存在執行緒安全問題時,并且查找較多用ArrayList.

3. 不存在執行緒安全問題時,增加或洗掉元素較多用LinkedList.

Map介面:

Map就是用來存盤“鍵(key)-值(value) 對”的. Map類中存盤的“鍵值對”通過鍵來標識,所以“鍵物件”不能重復.

Map 介面的實作類有HashMap、TreeMap、HashTable、Properties等.

---------------------------------------
                                 Map介面中常用的方法
            方法                                   說明
Object put(Object key, Object value)            存放鍵值對
Object get(Object key)                          通過鍵物件查找得到值物件
Object remove(Object key)                       洗掉鍵物件對應的鍵值對
boolean containsKey(Object key)                 Map容器中是否包含鍵物件對應的鍵值對
boolean containsValue(Object value)             Map容器中是否包含值物件對應的鍵值對
int size()                                      包含鍵值對的數量
boolean isEmpty()                               Map是否為空
void putAll(Map t)                              將的所有鍵值對存放到本map物件
void clear()                                    清空本map物件所有鍵值對
---------------------------------------

HashMap和HashTable:

HashMap采用哈希演算法實作,是Map介面最常用的實作類. 由于底層采用了哈希表存盤資料,我們要求鍵不能重復,
如果發生重復,新的鍵值對會替換舊的鍵值對. HashMap在查找、洗掉、修改方面都有非常高的效率.

HashTable類和HashMap用法幾乎一樣,底層實作幾乎一樣,只不過HashTable的方法添加了synchronized關鍵字確保執行緒同步檢查,效率較低.

HashMap與HashTable的區別:

  1. HashMap: 執行緒不安全,效率高.允許key或value為null.

  2. HashTable: 執行緒安全,效率低.不允許key或value為null.
---------------------------------------
例一:

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

public class TestMap {
	public static void main(String[] args) {
		
		Map<Integer,String> m1 = new HashMap<>();
		
		m1.put(1, "a");
		m1.put(2, "b");
		m1.put(3, "c");
		
		System.out.println(m1.get(1));
		
		System.out.println(m1.size());
		System.out.println(m1.isEmpty());
		System.out.println(m1.containsKey(2));
		System.out.println(m1.containsValue("c"));
		
		Map<Integer,String> m2 = new HashMap<>();
		m2.put(4, "++");
		m2.put(5, "**");
		
		m1.putAll(m2);
		
		System.out.println(m1);
		
		// 重復鍵時(根據equals方法判斷),前面鍵對應的值會被覆寫
		m1.put(3, "三");
		System.out.println(m1);
	}
}
---------------------------------------
例二:

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

public class TestMap2 {
	public static void main(String[] args) {
		
		Map<Integer,Employee> em1 = new HashMap<>();
		
		Employee e1 = new Employee(10001, "張一", 3211.11);
		Employee e2 = new Employee(10002, "張二", 123);
		Employee e3 = new Employee(10003, "張三", 2367.64);
		Employee e4 = new Employee(10001, "張四", 1022);
		
		em1.put(10001, e1);
		em1.put(10002, e2);
		em1.put(10002, e2);
		
		em1.get(10001).toString();
		
		em1.put(10001, e4);
		
		em1.get(10001).toString();				
	}
}

class Employee{
	
	private int id;
	private String ename;
	private double salary;
	
	public Employee(int id, String ename, double salary) {
		super();
		this.id = id;
		this.ename = ename;
		this.salary = salary;
	}
	
	@Override
	public String toString() {
		
		System.out.println("id:" + id + " name:"+ename);
		
		return super.toString();
	}
	
	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	public String getEname() {
		return ename;
	}
	
	public void setEname(String ename) {
		this.ename = ename;
	}
	
	public double getSalary() {
		return salary;
	}
	
	public void setSalary(double salary) {
		this.salary = salary;
	}
}
---------------------------------------

手動實作HashMap基礎功能:

---------------------------------------

public class Node2<K,V>{
	
	int hash;
	K key;
	V value;
	Node2 next;
	
}
---------------------------------------

public class TestHashMap<K,V> { 
	
	Node2[] table; // 位桶陣列,bucket array
	int size;   // 存放的鍵值對的個數
	
	public TestHashMap() {
		table = new Node2[16]; // 長度一般定義成2的整數冪
	}
	
	public void put(K key, V value) {
		// 定義新的節點
		Node2 newNode = new Node2();
		newNode.hash = myHash(key.hashCode(),table.length);
		newNode.key = key;
		newNode.value = value;
		newNode.next = null;
		// 取出hash值對應的那個陣列位置的初節點
		Node2 temp = table[newNode.hash];
		
		Node2 iterLast = null; // 正在遍歷的最后一個元素
		boolean keyRepeat = false;
		
		
		if(temp==null) {
			// 此處陣列元素為空,直接將新節點放進去
			table[newNode.hash] = newNode;
			size++;
			
		}else {
			// 此處陣列不為空,遍歷對應的鏈表
			
			while(temp!=null) {
				// 判斷key如果重復,則覆寫
				if(temp.key.equals(key)) {
					keyRepeat = true;
					temp.value = value; // 更新鍵對應的值
					break;
				}else {
					// key不重復,則遍歷下一個
					iterLast = temp;
					temp = temp.next;
				}	
			}
			
			if(!keyRepeat) {
				// 如果沒有發生key重復的情況,則添加到鏈表最后
				iterLast.next = newNode;
				size++;
			}
		}
		

	}
	
	public V get(K key) {
		
		int hash = myHash(key.hashCode(),table.length);
		V value = null;
		 
		if(table[hash]!=null) {
			Node2 temp = table[hash];
			
			while(temp!=null) {
				if(temp.key.equals(key)) {
					
					value = (V)temp.value;
					break;
					
				}else {
					temp = temp.next;
				}	
			}
		}
		
		return value;
	}
	
	public int myHash(int v,int length) {
//		System.out.println("hash in myHash:"+(v&(length-1))); // 直接位運算,效率高
//		System.out.println("hash in myHash:"+(v%(length-1))); // 取模運算,效率低
		return v&(length-1);
	}
	
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder("{");
		// 遍歷bucket陣列
		for(int i=0;i<table.length;i++) {
			Node2 temp = table[i];
			// 遍歷鏈表
			while(temp!=null) {
				sb.append(temp.key+":"+temp.value+", ");
				temp = temp.next;
			}
		}
		sb.setCharAt(sb.length()-2, '}');
		sb.deleteCharAt(sb.length()-1);
		System.out.println(sb);
		
		return super.toString();
	}
	
	public static void main(String[] args) {
		
		TestHashMap<Integer,String> m = new TestHashMap<>();
		
		m.put(10, "aa");
		m.put(20, "bb");
		m.put(30, "cc");
		m.put(20, "adawd");
		
		m.put(53, "ee");
		m.put(69, "tt");
		m.put(85, "oo");
		
		System.out.println(m);
		System.out.println(m.get(30));
	}
}
---------------------------------------

TreeMap的使用和Comparable介面的使用:

TreeMap是紅黑二叉樹的典型實作.我們打開TreeMap的原始碼,發現里面有一行核心代碼:
private transient Entry<K,V> root = null;

Entry(是TreeMap的內部類)里面存盤了本身資料、左節點、右節點、父節點、以及節點顏色. TreeMap的put()/remove()方法大量使用了紅黑樹的理論.

TreeMap和HashMap實作了同樣的介面Map,因此,用法對于呼叫者來說沒有區別.HashMap效率高于TreeMap;在需要排序的Map時才選用TreeMap.

---------------------------------------

import java.util.Map;
import java.util.TreeMap;

public class TestTreeMap {
	
	public static void main(String[] args) {
		
		Map<Integer,String> treemap1 = new TreeMap<>();
		treemap1.put(450, "aa");
		treemap1.put(55, "aa");
		treemap1.put(99, "aa");
		
		// 按照key遞增的方式排序
		for(Integer key:treemap1.keySet()) {
			System.out.println(key+"---"+treemap1.get(key));
		}
		
		Map<Emp,String> treemap2 = new TreeMap<>();
		treemap2.put(new Emp(10001,"xiaowang", 9000), "salary many");
		treemap2.put(new Emp(10002,"xiaoli", 4000), "salary low");
		treemap2.put(new Emp(10003,"xiaozhang", 9000), "salary many");
		
		for(Emp temp:treemap2.keySet()) {
			System.out.println(temp+"---"+treemap2.get(temp));
		}
	}
}

class Emp implements Comparable<Emp>{
	
	int id;
	String name;
	double salary;
	
	public Emp(int id, String name, double salary) {
		super();
		this.id = id;
		this.name = name;
		this.salary = salary;
	}

	@Override
	public int compareTo(Emp o) {
		
		if(this.salary>o.salary) {
			return 1;
		}else if(this.salary<o.salary) {
			return -1;
		}else {
			if(this.id>o.id) {
				return 1;
			}else if(this.id<this.id) {
				return -1;
			}
			return 0;
		}
	}
	
	@Override
	public String toString() {
		System.out.print("id:"+id+" salary:"+salary+" name:"+name);
		return "";
	}
}

---------------------------------------

Set介面:

Set介面繼承自Collection,Set介面中沒有新增方法,方法和Collection保持完全一致.我們在前面通過List學習的方法,在Set中仍然適用.

Set容器特點:無序、不可重復.無序指Set中的元素沒有索引,我們只能遍歷查找;不可重復指不允許加入重復的元素.更確切地講,
新元素如果和Set中某個元素通過equals()方法對比為true,則不能加入;甚至,Set中也只能放入一個null元素,不能多個.

Set常用的實作類有:HashSet、TreeSet等,我們一般使用HashSet.

HashSet的使用:

---------------------------------------

HashSet是采用哈希演算法實作,底層實際是用HashMap實作的(HashSet本質就是一個簡化版的HashMap),
因此,查詢效率和增刪效率都比較高.

--------------------------------------

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

public class TestHashSet {
	public static void main(String[] args) {
		
		Set<String> set1 = new HashSet<>();
		
		set1.add("aaa");
		set1.add("bbb");
		set1.add("aaa"); // 相同的元素不會被加入
		
		System.out.println(set1);
		
		set1.remove("bbb");
		System.out.println(set1);
		
		Set<String> set2 = new HashSet<>();
		set2.add("xiaozhang");
		set2.addAll(set1);
		System.out.println(set2);
		
		
	}
}
-------------------------------------

TreeSet的使用:

TreeSet底層實際是用TreeMap實作的,內部維持了一個簡化版的TreeMap,通過key來存盤Set的元素. 
TreeSet內部需要對存盤的元素進行排序,因此,我們對應的類需要實作Comparable介面.這樣,
才能根據compareTo()方法比較物件之間的大小,才能進行內部排序.

-------------------------------------

public class Test {
    public static void main(String[] args) {

        User u1 = new User(1001, "xiaowang", 18);
        User u2 = new User(2001, "xiaoli", 5);
        Set<User> set = new TreeSet<User>();
        set.add(u1);
        set.add(u2);

    }
}
 
class User implements Comparable<User> {
    int id;
    String uname;
    int age;
 
    public User(int id, String uname, int age) {
        this.id = id;
        this.uname = uname;
        this.age = age;
    }

    // 回傳0 表示 this == obj 回傳正數表示 this > obj 回傳負數表示 this < obj
    @Override
    public int compareTo(User o) {
        if (this.id > o.id) {
            return 1;
        } else if (this.id < o.id) {
            return -1;
        } else{
            return 0;
        }
    }
}

-------------------------------------

使用TreeSet要點:

(1) 由于是二叉樹,需要對元素做內部排序. 如果要放入TreeSet中的類沒有實作Comparable介面,則會拋出例外:java.lang.ClassCastException.

(2) TreeSet中不能放入null元素.

使用Iterator迭代器遍歷容器元素(List/Set/Map):

迭代器為我們提供了統一的遍歷容器的方式:

------------------------------------

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class TestInterator {
	public static void main(String[] args) {
		
		testIteratorList();
		testIteratorSet();
		testIteratorMap();
		
	}
	
	public static void testIteratorMap() {
		
		Map<Integer,String> map1 = new HashMap<>();
		map1.put(10, "aa");
		map1.put(20, "bb");
		map1.put(30, "cc");

		// 第一種遍歷Map的方式
		Set<Entry<Integer,String>> ss = map1.entrySet();
		
		for(Iterator<Entry<Integer,String>> iter = ss.iterator();iter.hasNext();) {
			Entry<Integer,String> temp = iter.next();
			
			System.out.println(temp.getKey()+"--"+temp.getValue());			
		}
		// 第二種遍歷Map的方式
		Set<Integer> keySet = map1.keySet();
		for(Iterator<Integer> iter=keySet.iterator();iter.hasNext();) {
			Integer key = iter.next();
			System.out.println(key+"----"+map1.get(key));
			
		}
		
	}
	
	public static void testIteratorList() {
		List<String> list = new ArrayList<>();
		
		list.add("aaa");
		list.add("bbb");
		list.add("ccc");
		// 使用Iterator遍歷List
		for(Iterator<String> iter=list.iterator();iter.hasNext();) {
			String temp = iter.next();
			System.out.println(temp);
		}
	}
	
	public static void testIteratorSet() {
		Set<String> set = new HashSet<>();
		
		set.add("aaa");
		set.add("bbb");
		set.add("ccc");
		// 使用Iterator遍歷Set
		for(Iterator<String> iter=set.iterator();iter.hasNext();) {
			String temp = iter.next();
			System.out.println(temp);
		}
	}
	
}
------------------------------------

iter.remove()在容器中洗掉此時迭代器所指向的元素

遍歷集合的方法總結:

-----------------------------------
for(int i=0;i<list.size();i++){  // list為集合的物件名
    String temp = (String)list.get(i);
    System.out.println(temp);
}


for(String temp : list) {
    System.out.println(temp);
}


for(Iterator iter= list.iterator();iter.hasNext();){
    String temp = (String)iter.next();
    System.out.println(temp);
}


Iterator  iter =list.iterator();
while(iter.hasNext()){
    Object obj =  iter.next();
    iter.remove();   // 如果要遍歷時,洗掉集合中的元素,建議使用這種方式!
    System.out.println(obj);
}
--------------------------------

for(String temp:set){
    System.out.println(temp);
}


for(Iterator iter = set.iterator();iter.hasNext();){
    String temp = (String)iter.next();
    System.out.println(temp);
}

--------------------------------
Map<Integer, Man> maps = new HashMap<Integer, Man>();

Set<Integer>  keySet =  maps.keySet();

for(Integer id : keySet){
    System.out.println(maps.get(id).name);
}


Set<Entry<Integer, Man>>  ss = maps.entrySet();
for (Iterator iterator = ss.iterator(); iterator.hasNext();) {
    Entry e = (Entry) iterator.next(); 
    System.out.println(e.getKey()+"--"+e.getValue());
}
--------------------------------    

Collections工具類:

類 java.util.Collections 提供了對Set、List、Map進行排序、填充、查找元素的輔助方法.

1. void sort(List)  // 對List容器內的元素排序,排序的規則是按照升序進行排序.

2. void shuffle(List)  // 對List容器內的元素進行隨機排列.

3. void reverse(List)  // 對List容器內的元素進行逆續排列 .

4. void fill(List, Object)  // 用一個特定的物件重寫整個List容器.

5. int binarySearch(List, Object)  // 對于順序的List容器,采用折半查找的方法查找特定物件.

Collections工具類的常用方法:

public class Test {
    public static void main(String[] args) {
        List<String> aList = new ArrayList<String>();
        for (int i = 0; i < 5; i++){
            aList.add("a" + i);
        }
        System.out.println(aList);
        Collections.shuffle(aList); // 隨機排列
        System.out.println(aList);
        Collections.reverse(aList); // 逆續
        System.out.println(aList);
        Collections.sort(aList); // 排序
        System.out.println(aList);
        System.out.println(Collections.binarySearch(aList, "a2")); 
        Collections.fill(aList, "hello");
        System.out.println(aList);
    }
}

表格資料存盤(map和list結合):

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class TestStoreData {
	
	public static void main(String[] args) {
		Map<String,Object> row1 = new HashMap<>();
		
		row1.put("id", 1001);
		row1.put("姓名", "張三");
		row1.put("薪水", 20000);
		row1.put("入職日期", "2020.8.5");
		
		Map<String,Object> row2 = new HashMap<>();
		
		row2.put("id", 1002);
		row2.put("姓名", "李四");
		row2.put("薪水", 21332);
		row2.put("入職日期", "2051.5.7");
			
		Map<String,Object> row3 = new HashMap<>();
		
		row3.put("id", 1003);
		row3.put("姓名", "王五");
		row3.put("薪水", 123123);
		row3.put("入職日期", "2023.9.8");
		
		List<Map<String,Object>> table1 = new ArrayList<>();
		
		table1.add(row1);
		table1.add(row2);
		table1.add(row3);
		
		for(Map<String,Object> row : table1) {
			Set<String> keySet = row.keySet();
			for(String key:keySet) {
				System.out.print(key+"--"+row.get(key)+"\t");
			}
			System.out.println();
		}
	}
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/148921.html

標籤:python

上一篇:死磕資料結構與演算法——查找演算法(java實作)。才疏學淺,如有錯誤,及時指正

下一篇:jfinal(1)—jfinal-undertow 下開發 jfinal專案

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more