1. 程式人生 > >Clloection接口 與List接口

Clloection接口 與List接口

修改元素 HA 存在 tla 長度 pub size class IT

collection接口:

collection是單列集合接口的根接口,該接口中又包含了多個集合接口,collection接口提供了很多操作集合的方法,比如添加元素的方法,刪除元素的方法,修改元素的方法等。

collection接口的常用方法
boolean add(E e) 將指定的對象添加到集合當中
bolean remove(object o) 刪除集合中的指定對象
bolean isEmpty() 判斷集合中是否包含元素
int size() 獲取集合中元素的個數
object [] toArray 返回包含集合中所有元素的數組
iterator<E> itterator 返回集合的叠代器,用於遍歷該集合2018-05-20

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;



public class collectionTest {
	public static void main(String[] args) {
		Collection  c=new ArrayList();//實例化實現了collection接口的類
		
		//向集合中添加數據
		c.add("A");
		c.add("B");
		c.add("C");
		//判斷集合中是否存在數據
		System.out.println(c.isEmpty());
		System.out.println(c.size());//獲取集合長度
		System.out.println("集合中元素為");
		Iterator it=c.iterator();//獲取集合叠代器對象
		while(it.hasNext()){//判斷集合中是否有下一個元素
			String s =(String) it.next();
			System.out.println(s);
		}
		
	}

}

List接口:

List 接口繼承了collection接口,List集合中允許出現重復的元素

而且存儲在該集合的元素是有序的。

List 接口常用實現類有ArrayList類與LinkedList類

add(int index,object obj) 向集合的index索引處添加obj對象
remove(int index) 移除index索引處的集合對象
set(int index,object obj) 修改index索引處的對象
get(int index) 獲取index索引出的集合對象
indexof(object obj) 獲取對象obj在集合中第一次出現的索引值
lastIndexof(object obj) 獲取對象obj在集合中最後一次出現的索引值
方法名稱 說明

ArryayList集合的使用:

Java中數值一旦創建其長度就不可改變,為了解決這個問題,集合框架定義了ArryaList類

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Collection  ls=new ArrayList ();
        ls.add("a");
        ls.add("b");
        ls.add("c");
        ls.add("d");
        
        System.out.println("a的索引為"+((ArrayList) ls).indexOf("a"));
        System.out.println("a的索引為"+((ArrayList) ls).lastIndexOf("a"));
        System.out.println("..........集合的元素的內容.........");
//        for(int i=0;i<ls.size();i++){
//         String s=(String) ((ArrayList) ls).get(i);
//         System.out.println(s);
//
//    }
        Iterator it=ls.iterator();
        while(it.hasNext()){
            String s =(String) it.next();
            System.out.println(s);
        }
}

LinkedlList集合的使用:

方法名稱 說明
object getFirst() 獲取集合中的第一個元素
object getLast() 獲取結合中的最後一個元素
void addFirst(E e) 將指定元素添加到集合的開頭
void addLalt(E a) 將指定元素添加到集合的結尾

ArryayList集合和LinkedlList集合的區別:

ArryayList集合是實現了動態數組數據結構的集合,LinkedlList集合是實現了鏈表數據結構的集合。對於遍歷集合元素操作,ArryayList集合效率優於LinkedlList集合

,對於增加和刪除元素的操作,LinkedlList集合效率優於ArryayList集合。

Clloection接口 與List接口