Collection集合常用方法总结

Collection借口是java集合框架的最顶层接口,它提供了大量的通用的集合操纵方法。collection接口是Sort接口和List接口的父接口。

Collection<String> col=new ArrayList<>();
//1.add 增加元素
col.add("yingying");
col.add("didi");
col.add("pingping");
col.add("wenqing");
System.out.println(col);
//2.remove--->移除指定的元素
col.remove("pingping");
System.out.println(col);
//3.contions-->是否包含指定元素
boolean b=col.contains("didi");
System.out.println(b);
//4.clear-->清除集合中所有内容
//5.hashCode-->获得集合的哈希码值(int类型)
int ha=col.hashCode();
System.out.println("hashCode:"+ha);
//6.isEmpty-->判断集合是否为空
boolean E=col.isEmpty();
System.out.println(E);

//---------------------------------------------------------------------

Collection<String> col1=new ArrayList<>();
col1.add("及时雨");
col1.add("智多星");

Collection<String> col2=new ArrayList<>();
col2.add("小李广");
col2.add("白日鼠");
//1.addAll-->col2的元素全部加到col1里
col1.addAll(col2);
System.out.println(col1);
System.out.println(col2);

Collection<String> col3=new ArrayList<>();
col3.add("小李广");
col3.add("白日鼠");
col3.add("花和尚");
//2.containsAll-->col3是否包含了col2全部的内容
boolean b=col3.containsAll(col2);
System.out.println(b);

//3.removeAll-->从col3里删除跟col2重合的所有内容
col3.removeAll(col2);
System.out.println(col3);

Collection<String> col4=new ArrayList<>();
col4.add("云中龙");
col4.add("玉麒麟");
col4.add("花和尚");
//4.retainAll-->仅保留col4与col3有重合的内容
col4.retainAll(col3);
System.out.println(col4);


猜你喜欢

转载自blog.csdn.net/Llyon/article/details/107598688