11JAVA基礎-集合

1、集合

`在這裏插入圖片描述java

2、Collection類

Collection 是單列的頂層類。
Collection是接口。
建立對象須要藉助多態。
//e爲集合中數據類型
//ArrayList是List的實現類
Collection<e> collection= new ArrayList<e>();

一、 Collection的經常使用方法

Collection<String> collection= new ArrayList<String>();
//向collection中增長元素
boolean ad = collecion.add(String value);
//從collection中刪除指定元素
boolean rem = collection.remove(String value);
//清除全部元素
void cle = collection.clear();
//判斷是否爲空
boolean isE = collection.isEmpty();
//集合中元素個數
int count = collection.size();

二、迭代器

Collection<String> collection= new ArrayList<String>();
//it 爲迭代器對象
Iterator it = collection.Iterator();
迭代器對象方法
boolean result =  it.hasNext();//是否有下一個
String result = it.next();//下一個元素

3、List

有序的集合,有索引
List<String> list = new ArrayLsit<String>();
特有方法
//獲取指定位置的元素
String s = list.get(int index);
//在指定位置加元素
String s = list.add(int index,String str);
//修改指定位置的元素
String s = list.set(int index,String str);
//刪除指定位置的元素
String s = list.remove(int index);

迭代器

List的迭代器能夠獲取倒序遍歷,
倒序遍歷前提:指針位於集合最後一個元素
ListIterator<E> lis = list.listIterator();
boolean  lis.hasPrevious();
E lis.previous();

4、List的遍歷方式

ArrayList<String> list = new ArrayList<E>();

一、使用迭代器

Iterator it = list.Iterator();
while(it.hasNext()){
	String value = it.next();
}

二、普通for

for(int i =0;i<list.size();i++){
		String s = list get(i);
}

三、加強for

for(String value : list){
		String s = value
}

5、ConcurrentModificationException異常

產生緣由:
	迭代器是依靠集合生成的。
	若是在使用迭代器的時候同時經過集合來修改集合元素個數,那麼迭代器沒法正確識別集合元素個數,致使報錯。
解決方案:
		一、經過迭代器修改個數
		二、獲取元素的不採用迭代器,直接使用for循環
兩種方案的差別:
		一、第一種加入的元直接加在當前迭代器指針位置的後一個
		二、第二種加載元素的最後一個

6、基本數據結構

一、棧

先進後出
進棧:壓棧
出棧:彈棧

二、隊列

先進先出

三、數組

查詢方便
增長數據的時候,每次都須要新建一個新的數組,而後將舊數組的數據增長或者刪除到新的數組。 比較耗時間。

四、鏈表

增刪方便,
每個元素保存元素數值、當前元素位置,下一個元素的位置
查詢數據的時候每次都須要從頭開始查詢,比較耗時間。
相關文章
相關標籤/搜索