Collection集合常用功能
生活随笔
收集整理的這篇文章主要介紹了
Collection集合常用功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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 com.learn.demo01.Collection;import java.util.ArrayList; import java.util.Collection; import java.util.HashSet;/*java.util.Collection接口所有單列集合的最頂層的接口,里邊定義了所有單列集合共性的方法任意的單列集合都可以使用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) {//創建集合對象,可以使用多態//Collection<String> coll = new ArrayList<>();Collection<String> coll = new HashSet<>();System.out.println(coll);//重寫了toString方法 []/*public boolean add(E e): 把給定的對象添加到當前集合中 。返回值是一個boolean值,一般都返回true,所以可以不用接收*/boolean b1 = coll.add("張三");System.out.println("b1:"+b1);//b1:trueSystem.out.println(coll);//[張三]coll.add("李四");coll.add("李四");coll.add("趙六");coll.add("田七");System.out.println(coll);//[張三, 李四, 趙六, 田七]/*public boolean remove(E e): 把給定的對象在當前集合中刪除。返回值是一個boolean值,集合中存在元素,刪除元素,返回true集合中不存在元素,刪除失敗,返回false*/boolean b2 = coll.remove("趙六");System.out.println("b2:"+b2);//b2:trueboolean b3 = coll.remove("趙四");System.out.println("b3:"+b3);//b3:falseSystem.out.println(coll);//[張三, 李四, 田七]/*public boolean contains(E e): 判斷當前集合中是否包含給定的對象。包含返回true不包含返回false*/boolean b4 = coll.contains("李四");System.out.println("b4:"+b4);//b4:trueboolean b5 = coll.contains("趙四");System.out.println("b5:"+b5);//b5:false//public boolean isEmpty(): 判斷當前集合是否為空。 集合為空返回true,集合不為空返回falseboolean b6 = coll.isEmpty();System.out.println("b6:"+b6);//b6:false//public int size(): 返回集合中元素的個數。int size = coll.size();System.out.println("size:"+size);//size:3//public Object[] 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());//true} }?
總結
以上是生活随笔為你收集整理的Collection集合常用功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 集合框架介绍
- 下一篇: Iterator接口介绍