Java源碼閱讀之Collection(容器)

Collection

什麼是Collection?

  • Collection是java提供的標準集合集,有一些具體類,可供直接使用,有一些抽象類,提供接口實現。

  • Collection繼承之 Iterable接口

  • Iterable接口抽象了兩個方法:

    • forEach() 循環遍歷
    • spliterator()
  • Collection定義了很多接口:

    • int size(); //容器大小
    • boolean isEmpty();//容器是否爲空
    • boolean contains(Object o);//容器是否包含Object對象
    • Iterator iterator();//迭代器(獲取集合類各個對象的一種方式)
    • Object[] toArray();//將集合的元素轉化爲數組
    • T[] toArray(T[] a);//將集合中的元素按照指定泛型(一致)進行互轉 例如:String[] str =strList.toArray(new String[strlist.size()]);
    • boolean add(E e);//是否可以添加一個元素
    • boolean remove(Object o);//是否可以刪除一個元素
    • boolean containsAll(Collection<?> c);//判斷集合c是否是該集合的子集
    • boolean addAll(Collection<? extends E> c);//將集合C中元素中的元素全部添加到集合中
    • boolean removeAll(Collection<?> c);//將集合C中的元素在集合中刪除
    • 方法default boolean removeIf(Predicate<? super E> filter)//刪除掉過濾函數
     default boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        boolean removed = false;
        final Iterator<E> each = iterator();
        while (each.hasNext()) {
            if (filter.test(each.next())) {
                each.remove();
                removed = true;
            }
        }
          return removed;
      }
       例如:
        public class Person {
            private String name;//姓名
            private Integer age;//年齡
            private String gender;//性別
            ... 
           //省略構造方法和getter、setter方法
            ...
        }
        
         Collection<Person> collection = new ArrayList();
         collection.add(new Person("張三", 22, "男"));
         collection.add(new Person("李四", 19, "女"));
         collection.add(new Person("王五", 34, "男"));
         collection.add(new Person("趙六", 30, "男"));
         
         collection.add(new Person("田七", 25, "女"));
         collection.removeIf(new Predicate<Person>() {
            @Override
            public boolean test(Person person) {
              return person.getAge()>=30;//過濾30歲以上的
            }
          });
         System.out.println(collection.toString());//查看結果
    
    • boolean retainAll(Collection<?> c);//取出兩個集合的交集
    • void clear();//清空集合中的元素
    • boolean equals(Object o);//比較集合中的元素是否相等
    • int hashCode();//集合的hashCode值
    • @Override
      default Spliterator spliterator() {
      return Spliterators.spliterator(this, 0);
      }//重寫Iterable序列號方法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章