主頁 >  其他 > 容器的介紹、實作及使用

容器的介紹、實作及使用

2020-10-03 04:01:20 其他

泛型:

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

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


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

以下是容器的介面層次結構圖:
-----------------------------------------
                     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/qita/150192.html

標籤:其他

上一篇:死磕資料結構與演算法——查找演算法(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)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more