contains方法

contains方法

package com.lichennan.collection;

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

/*
   深入Collection集合的contain方法:
   boolean contains(Object o)判断集合中是否包含某个对象。

   contains方法是用来判断集合中是否包含某个元素的方法,
   通过调用了equals方法进行比对。
   equals方法返回ture,就表示包含这个元素。
 */
public class CollectionTest04 {
    public static void main(String[] args) {
        //创建集合对象
        Collection c = new ArrayList();
        //向集合中存储元素
        String s1 = new String("abc");
        c.add(s1);
        String s2 = new String("def");
        c.add(s2);

        //集合中的元素个数
        System.out.println("元素的个数是:"+c.size());
        String x = new String("abc");
        System.out.println(c.contains(x));
    }
}

在这里插入图片描述

remove方法

package com.lichennan.collection;

import java.util.ArrayList;
import java.util.Collection;
//测试remove方法,底层调用了equals方法。
//结论:存放在一个集合中的类型,一定要重写equals方法
public class CollectionTest05 {
    
    public static void main(String[] args) {
        Collection cc = new ArrayList();
        String s1 = new String("hello");
        cc.add(s1);
        String s2 = new String("welcome");
        cc.add(s2);

        String s5 = new String("welcome");

        String s3 = new String("goodbye");
        cc.add(s3);
        System.out.println(cc.size());
        //看源码
        
        cc.remove(s5);
        System.out.println(cc.size());
        
        
    }
   
    
}

在这里插入图片描述

关于集合中元素的删除

package com.lichennan.collection;

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

/*
   关于集合元素的remove
   重点:当集合的结构发生改变时,迭代器必须重新获取,如果还是用以前老的迭代器,会出现异常
 */
public class CollectionTest06 {
    public static void main(String[] args) {
        Collection c  = new ArrayList();
        //注意:此时获取的迭代器,指向的是那是集合中没有元素状态下的迭代器。
        //一定要注意:集合结构只要发生改变,迭代器必须重新获取。
        c.add(1);
        c.add(2);
        c.add(3);
        Iterator it = c.iterator();
        while (it.hasNext()){
            Object obj =it.next();
            System.out.println(obj);
        }
        System.out.println("==============");

        Collection  c2 = new ArrayList();
        c2.add("abc");
        c2.add("def");
        c2.add("xyz");

        Iterator it2 = c2.iterator();
        while (it2.hasNext()){
            Object o = it2.next();
            it2.remove(); //使用迭代器来删除,删除的一定是迭代器指向的当前因素
            System.out.println(o);
        }
       
        System.out.println(c2.size());
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_46554776/article/details/106169691
今日推荐