泛型:
陣列就是一種容器,可以在其中放置物件或基本型別資料.
陣列的優勢:是一種簡單的線性序列,可以快速地訪問陣列元素,效率高.如果從效率和型別檢查的角度講,
陣列是最好的.
陣列的劣勢:不靈活.容量需要事先定義好,不能隨著需求的變化而擴容.
以下是容器的介面層次結構圖:
-----------------------------------------
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
標籤:其他
