首先了解一下ArrayList和LinkedList的區別:
1.ArrayList是基於數組,LinkedList是基於鏈表實現。
2.對於隨機訪問get和set,ArrayList優於LinkedList,因爲LinkedList要移動指針。
3.對於新增和刪除操作add和remove,LinkedList比較佔優勢,因爲ArrayList要移動數據
4.查找indexOf,,lastIndexOf,contains等,兩者差不多。
(注:這裏只是理論分析,事實上也不一定,比如ArrayList在末尾插入和刪除數據就不涉及到數據移動,不過還是有個建議,隨機訪問比較多的話一定要用ArrayList而不是LinkedList,如果需要頻繁地插入和刪除,應該考慮用LinkedList來提高性能)
ArrayList<Object> alist=new ArrayList<Object>();
添加數據: alist.add();
alist.add(1,"小明");//表示在索引1處添加數據
刪除數據: alist.remove(); 括號裏可以是索引,也可以是具體的值
查詢數據:
第一種方法:
for(Object obj : alist){
System.out.println(obj);
}
第二種方法:迭代器遍歷查詢
Iterator<Object> it=alist.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
LinkedList<Object> llist=new LinkedList<Object>();
添加數據: llist.add();
刪除數據: llist.remove();
查詢數據:
第一種方法:
for(Object obj : llist){
System.out.println(obj);
}
第二種方法:
Iterator<object> obj=llist.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
HashMap<Integerk,String> hm=new HashMap<Integer,String>();
添加鍵值對:hm.put(101,"小明");
hm.put(102,"小剛");
在添加某鍵時判斷某鍵是否存在:
if(hm.containsKey(101){//如果存在則返回true
System.out.println("鍵101已存在");
}else{
hm.put(101,"小芳");
}
查詢:使用迭代器遍歷所有鍵的集合
Iterator<Integer> it=keys.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
遍歷所有鍵值的集合
Collection<String> ct=hm.values();
Iterator<String> it2=ct.iterator();
while(it2.hasNext())
{
System.out.println(it2.next());
}
獲取所有的鍵值對集合
Set<Map.Entry<Integer,String>> entry=hm.entrySet();
Iterator<Map.Entry<Integer,String>> it3=entry.iterator();
while(it3.hasNext()){
Map.Entry<Integer,String> me=it3.next();//獲取正在遍歷的一個鍵值對
System.out.println("鍵:"+me.getKey()+" 值:"+me.getValue());
}
最後,歡迎訪問風格清新簡潔的輕博客網站[指尖一刻]