美文网首页
Collection中常用的方法

Collection中常用的方法

作者: 御都 | 来源:发表于2019-05-15 22:23 被阅读0次

【1 Collection的功能】存放的元素都是对象

  • 1.1添加
  • boolean add(E e)
  • boolean addAll(Collection<? extends E> c)
  • 1.2删除
  • void clear(),清空删除集合中所有的对象元素
  • boolean remove(Object o) 移除某个对象元素
  • boolean removeAll(Collection<?> c)移除多个对象元素
  • 1.3判断
  • boolean contains(Object o) 判断集合中是否有指定的某个元素
  • boolean containsAll(Collection c)判断集合中是否有多个元素
  • boolean isEmpty() 判断集合是否为空
  • 1.4获取
  • Iterator<E> iterator() 遍历,用来产生该集合的迭代器
  • 1.5交集
  • boolean retainAll(Collection c)保留交集的部分(非交集的对象元素去哪了?),交集为调用该方法的集合本身时返回为true,其余时候放回false,包括交集为null。交集的底层调用equals(),所以结果和equals()强相关
  • 1.6长度
  • int size() 集合中元素的个数
  • 1.7转换为对象数组
  • Object[] toArray() 把集合转换为一个对象数组
    【2 举例】
    *2.1 boolean retain(Collection c)
package it.cast01;

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

public class CollectionDemo5 {
    public static void main(String[] args) {
        Collection c = new ArrayList();
        c.add("hello");
        c.add("world");
        Collection c2 = new ArrayList();
        c2.add("hello");
        c2.add("world");
        c2.add("java");
        Collection c3 = new ArrayList();
        c3.add("home");
        
        System.out.println(c.retainAll(c2));
        System.out.println("c = "+c);
        System.out.println(c.retainAll(c3));
        System.out.println("c = "+c);
    }
}

运行结果为:

false
c = [hello, world]
true
c = []

相关文章

网友评论

      本文标题:Collection中常用的方法

      本文链接:https://www.haomeiwen.com/subject/uxhvaqtx.html