本节将大概用代码案例简单总结一下 Collection 接口中的一些方法,我们会以他的实现类 Arraylist 为例创建对象。一起来看看吧!
import java.util.ArrayList;
import java.util.Collection;/*** @Author:Aniu* @Date:2022/12/4 16:19* @description TODO*/
public class Demo {public static void main(String[] args) {Collection coll = new ArrayList();// add(Object e) 增加coll.add("aniu");coll.add(123); //自动装箱coll.add(new String("miao"));System.out.println(coll);System.out.println("------------------");// addAll() 将另一个集合中的元素添加到当前集合中Collection coll1 = new ArrayList();coll1.add(123);coll1.add("bb");coll.addAll(coll1);System.out.println(coll);}
}
// size() 求添加的元素个数Collection coll = new ArrayList();coll.add("aniu");coll.add(123); //自动装箱coll.add(new String("miao"));System.out.println(coll.size());
Collection coll = new ArrayList();
coll.add("aniu");
coll.add(123); //自动装箱
coll.add(new String("miao"));
//isEmpty() 判断当前集合是否为空
System.out.println(coll.isEmpty());
Collection coll = new ArrayList();
coll.add("aniu");
coll.add(123); //自动装箱
coll.add(new String("miao"));
//clear() 清空集合元素
System.out.println(coll.clear());
Collection coll = new ArrayList();
coll.add("aniu");
coll.add(123); //自动装箱
coll.add(new String("miao"));
// contains() 判断对象是否在当前集合中
System.out.println(coll.contains(new String("aniu")));
这里要注意的是,contains本质上是用equals比较的,因此,对于自定义对象,要记得重写equals方法!
Collection coll = new ArrayList();
coll.add("aniu");
coll.add(123); //自动装箱
coll.add(new String("miao"));
Collection coll1 = new ArrayList();
coll1.add(123);
coll1.add("aniu");
// containsAll() 判断形参集合中的元素是否在当前集合中
System.out.println(coll.containsAll(coll1));
本质上依旧是用equals一个个比较
Collection coll = new ArrayList();
coll.add("aniu");
coll.add(123); //自动装箱
coll.add(456);
coll.add(new String("miao"));
// remove() 移除
coll.remove(123);
System.out.println(coll);
System.out.println("------------");Collection coll1 = new ArrayList();
coll1.add(456);
coll1.add(new String("miao"));
// removeAll() 从当前集合中移除形参集合中的所有元素,即差集
coll.removeAll(coll1);
System.out.println(coll);
removeAll() 相当于求差集,那么也有对应求交集的!
Collection coll = new ArrayList();
coll.add("aniu");
coll.add(123); //自动装箱
coll.add(new String("miao"));
Collection coll1 = new ArrayList();
coll1.add(123);
coll1.add(new String("miao"));
// retainAll() 即求交集
coll.retainAll(coll1);
System.out.println(coll);
Collection coll = new ArrayList();
coll.add("aniu");
coll.add(123); //自动装箱
Collection coll1 = new ArrayList();
coll1.add(123);
coll.add("aniu");
// equals() 判断两个集合是否相等,因为这里使用ArrayList()实现,因此要考虑顺序
System.out.println(coll.equals(coll1));
Collection coll = new ArrayList();
coll.add("aniu");
coll.add(123); //自动装箱
// toArray() 集合转数组
Object[] arr = coll.toArray();
System.out.println(Arrays.toString(arr));
既然说到了集合转数组,这里就说一下数组转集合!
List list = Arrays.asList(new String[]{"aniu", "tom"});System.out.println(list);
本来关于这些api是不想总结的,像String中的一些api,和其他语言中的差不多,我就没总结!集合中的方法名与其他语言稍微有不同,这里快速过一下。
如果你觉得博主写的还不错的话,可以关注一下当前专栏,博主会更完这个系列的哦!也欢迎订阅博主的其他好的专栏。
🏰系列专栏
👉软磨 css
👉硬泡 javascript
👉flask框架快速入门
下一篇:C语言第十三课:初阶指针