1. 程式人生 > 其它 >集合(1)Collection介面的使用

集合(1)Collection介面的使用

集合的概念:物件的容器,定義了對多個物件進行操作的常用方法,可實現陣列的功能。

和陣列的區別:①陣列長度固定,集合長度不固定

         ②陣列可以儲存基本型別和引用型別,而集合只能儲存引用型別。

Collection體系:

 

Collection介面的使用:①新增元素--add();②刪除元素--remove();③遍歷元素--可用增強的for迴圈,也可使用迭代器Iterator。

/**
 * Collection介面的使用
 * 1.新增元素
 * 2.刪除元素
 * 3.遍歷元素
 * 4.判斷
 * @author 長空扯淡
 */
public class Demo01 {
    
public static void main(String[] args) { //建立集合 Collection collection = new ArrayList(); // * 1.新增元素 collection.add("西瓜"); collection.add("香蕉"); collection.add("火龍果"); System.out.println(collection);//輸出--[西瓜, 香蕉, 火龍果] System.out.println("===========================");
// * 2.刪除元素 collection.remove("香蕉"); //collection.clear();//清除 System.out.println("刪除之後:"+collection.size());//輸出--刪除結果:2 System.out.println("==========================="); // * 3.遍歷元素【重點】 //3.1用增強的for迴圈 for(Object obj:collection){ System.out.println(obj);//輸出--西瓜
}                     火龍果 System.out.println(
"==========================="); //3.2使用迭代器(專門用來遍歷集合的一種方式) /* hasNext();有沒有下一個元素 next();獲取下一個元素 remove();刪除當前元素 */ Iterator it = collection.iterator(); while(it.hasNext()){ String s = (String)it.next(); System.out.println(s);        //輸出--西瓜
                                 火龍果
//不允許使用collection.remove();的刪除方法,可以使用it.remove(); //it.remove(); } System.out.println(collection.size());//輸出結果--2 // * 4.判斷 System.out.println("==========================="); System.out.println(collection.contains("西瓜"));//輸出--true System.out.println(collection.isEmpty());//輸出--false } }

也可以用add()方法新增物件

//假設Student類已經定義好
Student s1 = new Student("愛麗絲",17);
        Student s2 = new Student("桐人",17);
        Student s3 = new Student("優吉歐",17);

        //新建Collection物件
        Collection collection = new ArrayList();
        //1.新增資料
        collection.add(s1);
        collection.add(s2);
        collection.add(s3);
        System.out.println(collection);
        System.out.println(collection.size());