Collection集合常用方法运行示例
boolean add(E e)
import java.util.ArrayList; import java.util.Collection; public class CollectionDemo_02 { public static void main(String[] args) { //创建集合对象 Collection<String> c = new ArrayList<String>(); //boolean add(E e):添加元素 System.out.println(c.add("hello")); System.out.println(c.add("world")); System.out.println(c.add("world")); //输出集合对象 System.out.println(c); /* 运行结果: true true true [hello, world, world] 为什么运行结果全为true呢? 通过查看源码后,add方法返回值永远是true. public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } */ } }
boolean remove(Object o)
public class CollectionDemo_02 { public static void main(String[] args) { //创建集合对象 Collection<String> c = new ArrayList<String>(); //boolean add(E e):添加元素 c.add("hello"); c.add("world"); c.add("java"); //boolean remove(Object o):从集合中移除指定的元素 System.out.println(c.remove("world")); System.out.println(c.remove("javaee")); //输出集合对象 System.out.println(c); /* 运行结果: true false 集合中没有"javaee"元素,所以false [hello, java] 成功删除元素"world" */ } }
void clear() :清空集合中的元素 (添加的元素在前面代码中)
//void clear() : 清空集合中的元素 c.clear(); //输出集合对象 System.out.println(c); /* 运行结果: [] */
boolean contains(Object o) :判断集合中是否存在指定的元素
//boolean contains(Object o):判断集合中是否存在指定的元素 System.out.println(c.contains("world")); System.out.println(c.contains("javaee")); //输出集合对象 System.out.println(c); /* 运行结果: true //集合中存在元素world false //集合中没有元素javaee [hello, world, java] */
boolean isEmpty():判断集合是否为空
//boolean isEmpty():判断集合是否为空 System.out.println(c.isEmpty()); System.out.println(c); c.clear(); System.out.println(c.isEmpty()); //输出集合对象 System.out.println(c); /* 运行结果: false // 不为空 [hello, world, java] true [] */
int size() : 集合的长度,也就是集合中元素的个数
//int size() : 集合的长度,也就是集合中元素的个数 System.out.println(c.size()); //输出集合对象 System.out.println(c); /* 运行结果: 3 [hello, world, java] */
学习的博客多用于在笔记中,防止笔记过于臃肿,所以将样例及运行结果放在博客中,后以超链接的形式记录在笔记中,所以有些博文过于单薄。如果有小伙伴遇到问题欢迎评论,看到就会回复,学渣一枚,加油努力。