1,Collection集合常用的方法
void clear()清空集合中的元素
boolean add(E e)添加元素
boolean isEmpty()判断集合是否为空
int size()集合的长度,也就是集合中元素的个数
boolean removeIf(Object o)根据条件进行移除void
boolean remove(Object o)从集合中移除指定的元素
boolean contains(Object o)判断集合中是否存在指定的元素
2,Collection集合的遍历
迭代器介绍
迭代器,集合的专用遍历方式
Iterator iterator(): 返回此集合中元素的迭代器,通过集合对象的iterator()方法得到
Iterator中的常用方法
boolean hasNext(): 判断当前位置是否有元素可以被取出
E next(): 获取当前位置的元素,将迭代器对象移向下一个索引位置
public class IteratorDemo1 {
public static void main(String[] args) {
//创建集合对象
Collection<String> c = new ArrayList<>();
//添加元素
c.add("hello");
c.add("world");
c.add("java");
c.add("javaee");
//Iterator<E> iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
Iterator<String> it = c.iterator();
//用while循环改进元素的判断和获取
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
}
}
3,数组和集合的区别
相同点
都是容器,可以存储多个数据
不同点
数组的长度是不可变的,集合的长度是可变的
数组可以存基本数据类型和引用数据类型
集合只能存引用数据类型,如果要存基本数据类型,需要存对应的包装类