1. 程式人生 > 實用技巧 >JavaSE進階--Collection集合

JavaSE進階--Collection集合

Collection集合

1.1 集合概述


我們已經學習過並使用過集合ArrayList ,那麼集合到底是什麼呢?

  • 集合:集合是java中提供的一種容器,可以用來儲存多個數據


集合和陣列既然都是容器,它們有啥區別呢?

  • 陣列的長度是固定的。集合的長度是可變的。
    • int[] arr = new int[10];
    • Student[] stu = new Student[3];
    • ArrayList
  • 陣列中儲存的是同一型別的元素,可以儲存基本資料型別值。集合儲存的都是物件。而且物件的型別可以不一致。在開發中一般當物件多的時候,使用集合進行儲存。
int[] arr = new int[10];
Student[] stu = new Student[3];
ArrayList<Student><String><Integer>

1.2  集合框架


1.3 Collection 常用功能


Collection是所有單列集合的父介面,因此在Collection中定義了單列集合(List和Set)通用的一些方法,這些方法可用於操作所有的單列集合。方法如下:

  • public boolean add(E e):  把給定的物件新增到當前集合中 。
  • public void clear() :清空集合中所有的元素。
  • public boolean remove(E e): 把給定的物件在當前集合中刪除。
  • public boolean contains(E e): 判斷當前集合中是否包含給定的物件。
  • public boolean isEmpty()
    : 判斷當前集合是否為空。
  • public int size(): 返回集合中元素的個數。
  • public Object[] toArray(): 把集合中的元素,儲存到陣列中。


方法演示:

package 集合和泛型.Collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;

/**
 * 在Collection介面定義著單列集合框架中最最共性的內容。
 *
 * 共性方法:
 *      public boolean add(E e):  把給定的物件新增到當前集合中 。
 *      public void clear() :清空集合中所有的元素。
 *      public boolean remove(E e): 把給定的物件在當前集合中刪除。
 *      public boolean contains(E e): 判斷當前集合中是否包含給定的物件。
 *      public boolean isEmpty(): 判斷當前集合是否為空。
 *      public int size(): 返回集合中元素的個數。
 *      public Object[] toArray(): 把集合中的元素,儲存到陣列中。
 */
public class Demo01Collection {
    public static void main(String[] args) {
        demo01();
    }

    public static void demo01(){
        // 建立集合物件,可以使用多型
        // Collection<String> coll = new ArrayList<>();
        Collection<String> coll = new HashSet<>();
        System.out.println(coll);
        // add 方法
        boolean b1 = coll.add("張三");
        System.out.println(b1);
        System.out.println(coll);
        coll.add("李四");
        coll.add("李四");     // HashSet會自動去重
        coll.add("王五");
        coll.add("趙六");
        coll.add("田七");
        System.out.println(coll);

        // remove方法 : 存在元素會刪除元素返回True,不存在刪除失敗返回False
        boolean b2 = coll.remove("趙六");
        System.out.println(b2);
        System.out.println(coll);
        boolean b3 = coll.remove("趙四");
        System.out.println(b3);

        // contains() 方法  是否包含某個元素,包含True,否則false
        boolean b4 = coll.contains("張三");
        System.out.println(b4);
        boolean b5 = coll.contains("張六");
        System.out.println(b5);

        // isEmpty()方法   :為空True,不為空True
        boolean b6 = coll.isEmpty();
        System.out.println(b6);

        // size()方法
        System.out.println(coll.size());

        //toArray(): 把集合中的元素,儲存到陣列中。
        Object [] arr = coll.toArray();
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

        //public void clear() :清空集合中所有的元素。
        coll.clear();
        System.out.println(coll);
        System.out.println(coll.isEmpty());
    }
}

tips: 有關Collection中的方法可不止上面這些,其他方法可以自行檢視API學習。