1. 程式人生 > >15 API-集合(Collection(功能,迭代器),List(List特有迭代器,併發異常),常見資料結構圖示(棧,佇列,陣列,連結串列))&物件陣列

15 API-集合(Collection(功能,迭代器),List(List特有迭代器,併發異常),常見資料結構圖示(棧,佇列,陣列,連結串列))&物件陣列

1:物件陣列(掌握)

(1)陣列既可以儲存基本資料型別,也可以儲存引用型別。它儲存引用型別的時候的陣列就叫物件陣列。


(2)案例:

用陣列儲存5個學生物件,並遍歷陣列。

學生的物件

public class Student {
	// 成員變數
	private String name;
	private int age;

	// 構造方法
	public Student() {
		super();
	}

	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	// 成員方法
	// getXxx()/setXxx()
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
}

物件陣列存數5個學生的物件並遍歷
/*
 * 我有5個學生,請把這個5個學生的資訊儲存到陣列中,並遍歷陣列,獲取得到每一個學生資訊。
 *		 學生:Student
 *		 成員變數:name,age
 *		 構造方法:無參,帶參
 *		 成員方法:getXxx()/setXxx()
 *		 儲存學生的陣列?自己想想應該是什麼樣子的?
 * 分析:
 * 		A:建立學生類。
 * 		B:建立學生陣列(物件陣列)。
 * 		C:建立5個學生物件,並賦值。
 * 		D:把C步驟的元素,放到陣列中。
 * 		E:遍歷學生陣列。
 */
public class ObjectArrayDemo {
	public static void main(String[] args) {
		// 建立學生陣列(物件陣列)。
		Student[] students = new Student[5];
		// for (int x = 0; x < students.length; x++) {
		// System.out.println(students[x]);
		// }
		// System.out.println("---------------------");

		// 建立5個學生物件,並賦值。
		Student s1 = new Student("林青霞", 27);
		Student s2 = new Student("風清揚", 30);
		Student s3 = new Student("劉意", 30);
		Student s4 = new Student("趙雅芝", 60);
		Student s5 = new Student("王力巨集", 35);

		// 把C步驟的元素,放到陣列中。
		students[0] = s1;
		students[1] = s2;
		students[2] = s3;
		students[3] = s4;
		students[4] = s5;

		// 看到很相似,就想迴圈改
		// for (int x = 0; x < students.length; x++) {
		// students[x] = s + "" + (x + 1);
		// }
		// 這個是有問題的

		// 遍歷
		for (int x = 0; x < students.length; x++) {
			//System.out.println(students[x]);
			
			Student s = students[x];
			System.out.println(s.getName()+"---"+s.getAge());
		}
	}
}



2:集合(Collection)(掌握)


       (1)集合的由來?

              我們學習的是Java -- 面向物件 -- 操作很多物件 -- 儲存 -- 容器(陣列和StringBuffer)-- 陣列

              而陣列的長度固定,所以不適合做變化的需求,Java就提供了集合供我們使用。

       (2)集合和陣列的區別?

              A:長度區別

                     陣列固定

                     集合可變

              B:內容區別

                     陣列可以是基本型別,也可以是引用型別

                     集合只能是引用型別

              C:元素內容

                     陣列只能儲存同一種類型

                     集合可以儲存不同型別(其實集合一般儲存的也是同一種類型)

       (3)集合的繼承體系結構?

              由於需求不同,Java就提供了不同的集合類。這多個集合類的資料結構不同,但是它們都是要提供儲存和遍歷功能的,

              我們把它們的共性不斷的向上提取,最終就形成了集合的繼承體系結構圖。

              Collection

                     |--List

                            |--ArrayList

                            |--Vector

                            |--LinkedList

                     |--Set

                            |--HashSet

                            |--TreeSet




(4)Collection的功能概述()

A:新增功能 

boolean add(Object obj):新增一個元素
boolean addAll(Collection c):新增一個集合的元素
  

B:刪除功能

void clear():移除所有元素
boolean remove(Object o):移除一個元素
boolean removeAll(Collection c):移除一個集合的元素

C:判斷功能

boolean contains(Object o):判斷集合中是否包含指定的元素
 * boolean containsAll(Collection c):判斷集合中是否包含指定的集合元素(只有包含所有的元素,才叫包含)
 * boolean isEmpty():判斷集合是否為空

D:獲取功能

Iterator<E> iterator()(重點)

E:長度功能

int size():元素的個數
 * 面試題:陣列有沒有length()方法呢?字串有沒有length()方法呢?集合有沒有length()方法呢?

陣列:.length      字串:.length()         集合: .size()

F:交集(瞭解)

boolean retainAll(Collection c):A集合對B集合做交集,最終的結果儲存在A中,B不變。返回值表示的是A是否發生過改變。

G:把集合轉陣列(瞭解)

Object[] toArray()

(5)Collection集合的遍歷
A:把集合轉陣列(瞭解)
B:迭代器(集合專用方式)

(6)迭代器

A:是集合的獲取元素的方式。

Iterator iterator():迭代器,集合的專用遍歷方式
 * Object next():獲取元素,並移動到下一個位置。
 * NoSuchElementException:沒有這樣的元素,因為你已經找到最後了。

NoSuchElementException 不要多次使用it.next()方法
 * boolean hasNext():如果仍有元素可以迭代,則返回 true。

B:是依賴於集合而存在的。
C:迭代器的原理和原始碼。

a:為什麼定義為了一個介面而不是實現類?


b:看了看迭代器的內部類實現。

簡易內部原始碼

public interface Iterator {
	boolean hasNext();
	Object next(); 
}

public interface Iterable {
    Iterator iterator();
}

public interface Collection extends Iterable {
	//Iterator iterator();
}

public interface List extends Collection {
	//Iterator iterator();
}

public class ArrayList implements List {
	public Iterator iterator() {
        return new Itr();
    }
    
    private class Itr implements Iterator {
    	public boolean hasNext() {}
		public Object next(){} 
    }
}


Collection c = new ArrayList();
c.add("hello");
c.add("world");
c.add("java");
Iterator it = c.iterator();	 //new Itr();
while(it.hasNext()) {
	String s = (String)it.next();
	System.out.println(s);
}


       (7)Collection集合的案例(遍歷方式迭代器)

              集合的操作步驟:

                     A:建立集合物件

                     B:建立元素物件

                     C:把元素新增到集合

                     D:遍歷集合

              A:儲存字串並遍歷

                     importjava.util.Collection;

                     importjava.util.ArrayList;

                     importjava.util.Iterator;

                     publicclass CollectionDemo {

                            publicstatic void main(String[] args) {

                                   //建立集合物件

                                   Collectionc = new ArrayList();

                                   //建立並新增元素

                                   c.add("hello");

                                   c.add("world");

                                   c.add("java");

                                   //遍歷集合

                                   Iteratorit = c.iterator();

                                   while(it.hasNext()){

                                          Strings =(String) it.next();

                                          System.out.println(s);

                                   }

                            }

                     }

              B:儲存自定義物件並遍歷

                     publicclass Student {

                            privateString name;

                            privateint age;

                            publicStudent(){}

                            publicStudent(String name,int age) {

                                   this.name= name;

                                   this.age= age;

                            }

                            //getXxx()/setXxx()

                     }

                     importjava.util.Collection;

                     importjava.util.ArrayList;

                     importjava.util.Iterator;

                     publicclass StudentDemo {

                            publicstatic void main(String[] args) {

                                   //建立集合物件

                                   Collectionc = new ArrayList();

                                   //建立學生物件

                                   Students1 = new Student("林青霞",27);

                                   Students2 = new Student("風清揚",30);

                                   Students3 = new Student("劉意",30);

                                   Students4 = new Student("武鑫",25);

                                   Students5 = new Student("劉曉曲",16);

                                   //新增元素

                                   c.add(s1);

                                   c.add(s2);

                                   c.add(s3);

                                   c.add(s4);

                                   c.add(s5);

                                   //遍歷集合

                                   Iteratorit = c.iterator();

                                   while(it.hasNext()){

                                          Students = (Student)it.next();

                                          System.out.println(s.getName()+"---"+s.getAge());

                                   }

                            }

                     }



3:集合(List)(掌握)

(1)List是Collection的子介面
特點:有序(儲存順序和取出順序一致),可重複。
(2)List的特有功能:()

A:新增功能

void add(int index,Object element):在指定位置新增元素

B:刪除功能

Object remove(int index):根據索引刪除元素,返回被刪除的元素

C:獲取功能

Object get(int index):獲取指定位置的元素

D:迭代器功能

ListIterator listIterator():List集合特有的迭代器

E:修改功能

Object set(int index,Object element):根據索引修改元素,返回被修飾的元素

(3)List集合的特有遍歷功能
A:由size()和get()結合。
B:程式碼演示
//建立集合物件
List list = new ArrayList();

//建立並新增元素
list.add("hello");
list.add("world");
list.add("java");

//遍歷集合
Iterator it = list.iterator();
while(it.hasNext()) {
String s =(String) it.next();
System.out.println(s);
}
System.out.println("----------");

for(int x=0; x<list.size(); x++) {
String s =(String) list.get(x);
System.out.println(s);
}
(4)列表迭代器的特有功能;(瞭解)
boolean hasPrevious()  +++++++   Eprevious()  配合逆向迭代
可以逆向遍歷,但是要先正向遍歷,所以無意義,基本不使用。
void add(E e)將指定的元素插入列表(可選操作)。
void set(E e)指定元素替換 nextprevious 返回的最後一個元素(可選操作)。
void remove()從列表中移除由 nextprevious 返回的最後一個元素(可選操作)。


(5)併發修改異常
A:出現的現象  ---併發修改異常
迭代器遍歷集合,集合修改集合元素
B:原因
迭代器是依賴於集合的,而集合的改變迭代器並不知道。
C:解決方案
a:迭代器遍歷,迭代器修改(ListIterator)
元素新增在剛才迭代的位置
b:集合遍歷,集合修改(size()和get())
元素新增在集合的末尾

(6)常見資料結構

A:棧 先進後出

B:佇列 先進先出
C:陣列 查詢快,增刪慢

D:連結串列 查詢慢,增刪快

棧和佇列


陣列和連結串列


(7)List的子類特點(面試題)
ArrayList
底層資料結構是陣列,查詢快,增刪慢。
執行緒不安全,效率高。
Vector
底層資料結構是陣列,查詢快,增刪慢。
執行緒安全,效率低。
LinkedList
底層資料結構是連結串列,查詢慢,增刪快。
執行緒不安全,效率高。

到底使用誰呢?看需求?
分析:
要安全嗎?
要:Vector(即使要,也不使用這個,後面再說)
不要:ArrayList或者LinkedList
查詢多;ArrayList
增刪多:LinkedList

什麼都不知道,就用ArrayList。
(8)List集合的案例(遍歷方式 迭代器和普通for)
A:儲存字串並遍歷
B:儲存自定義物件並遍歷