java:Collection集合的基本方法运用(添加/删除/包含/清空等)

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qq_24644517/article/details/82948714

 A:案例演示    
        基本功能演示    
        boolean add(E e)
        boolean remove(Object o)
        void clear()
        boolean contains(Object o)
        boolean isEmpty()
        int size()

 B:注意:
        collectionXxx.java使用了未经检查或不安全的操作.
        注意:要了解详细信息,请使用 -Xlint:unchecked重新编译.
        java编译器认为该程序存在安全隐患
        温馨提示:这不是编译失败,所以先不用理会,等学了泛型你就知道了

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

import com.heima.bean.Student;


@SuppressWarnings({ "rawtypes", "unchecked" })
public class Demo2_Collection {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
//       demo1();
		Collection cl=new ArrayList();//父类引用指向子类对象
		cl.add("abc0");
		cl.add("abc1");
		cl.add("abc2");
		cl.add("abc3");
		System.out.println("collection 中的元素数:"+cl.size());//返回此 collection 中的元素数。
		System.out.println("删除前:"+cl);
		cl.remove("abc1");//删除集合中指定元素
		System.out.println("删除后:"+cl);
		System.out.println("判断字符串是否包含在集合内:"+cl.contains("abc0"));//判断字符串是否包含在集合内,如果此 collection 包含指定的元素,则返回 true。
		cl.clear();//清空集合
		System.out.println("清空元素后打印:"+cl);
		System.out.println("判断是否有元素:"+cl.isEmpty());//如果此 collection 不包含元素,则返回 true。
		
		
	}

	public static void demo1() {
		//		add方法如果是list集合一直返回true,因为list集合中可以存储重复元素的
		//		如果是set集合,当存储重复元素时,会返回false
		//		ArrayList的父类的父类重写了toString方法,所以在打印对象引用的时候,输出的结果不是Object类中toString的结果
				Collection cl=new ArrayList();//父类引用指向子类对象
				boolean b1=cl.add("abc");
				boolean b2=cl.add(true);//添加基本类型,会自动装箱new boolean(true);
				boolean b3=cl.add(100);
				boolean b4=cl.add(new Student("小米",1));
				System.out.println(b1);
				System.out.println(b2);
				System.out.println(b3);
				System.out.println(b4);
				System.out.println(cl);
	}

}

猜你喜欢

转载自blog.csdn.net/qq_24644517/article/details/82948714