目录
Collection接口常用方法,以实现子类ArrayList来演示
Collection接口
Collection接口实现类的特点
-
Collection接口的实现子类可以存放多个元素,每个元素可以是Object
-
有些Collection接口的实现类,可以存放重复的元素,有些不可以
-
有些Collection接口的实现类,是有序的(List),有些不是有序的(Set)
-
Collection接口没有直接的实现子类,是通过它的子接口Set 和 List来实现的
Collection接口常用方法,以实现子类ArrayList来演示
- add():添加单个元素
public class Test02 {
public static void main(String[] args) {
Collection collection = new ArrayList();
collection.add("jack");
//实际上是List.add(new Integer(10))
collection.add(10);
collection.add(true);
System.out.println(collection);
}
}
-
remove():删除指定元素
-
contains():查找元素是否存在
-
size():获取元素个数
-
get(int index):获取指定index位置上的元素
-
isEmpty():判断是否为空
-
clear():清空
-
addAll():添加多个元素
-
containsAll():查找多个元素是否都存在
-
removeAll():删除多个元素
使用Iterator(迭代器)遍历元素
-
Iterator对象称为迭代器,主要用于遍历 Collection 集合中的元素
-
所有实现了 Collection 接口的集合类都有一个 iterator() 方法,用以返回一个实现了Iterator接口的对象,即可以返回一个迭代器
-
Iterator 仅用于遍历集合,Iterator 本身并不存放对象
-
快捷键生成 while 循环:itit
-
显示所有快捷键的快捷键:ctrl+j
迭代器的执行原理
Iterator iterator = coll.iterator(); //得到一个集合迭代器
// hasNext() :判断是否还有下一个元素
while(Iterator.hasNext()) {
//next():(1) 指针下移 (2) 将下移以后集合位置上的元素返回
System.out.println(Iterator.next());
}
提示:在调用 iterator.next() 方法之前必须调用 iterator.hasNext() 进行检测。若不调用,且下一条记录无效,直接调用iterator.next()会抛出NoSuchElementException异常
System.out.println(col);
输出 col 集合时调用的是 Collection 的实现类 AbstractCollection 重写Object类的 toString() 方法
System.out.println(obj);
输出 obj 时调用的是Book 类中的 toString() 方法
public class Demo03 {
public static void main(String[] args) {
Collection col = new ArrayList();
col.add(new Book("三国演义","罗贯中",10.1));
col.add(new Book("小李飞刀","古龙",5.1));
col.add(new Book("三国演义","罗贯中",34.6));
System.out.println(col);
Iterator iterator = col.iterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
System.out.println(obj);
}
}
}
class Book{
private String name;
private String author;
private double price;
public Book(String name, String author, double price) {
this.name = name;
this.author = author;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
'}';
}
}
增强for循环
-
增强for循环,可以代替 iterator 迭代器,特点:增强for循环就是简化版的iterator,底层仍然是迭代器,本质一样。**只能用来遍历集合或数组**。
-
快捷键:集合或数组.for
-
基本语法
for(元素类型 元素名:集合名或数组名) {
访问元素
}
public class Demo04 {
public static void main(String[] args) {
Collection col = new ArrayList();
col.add(new Book("三国演义","罗贯中",10.1));
col.add(new Book("小李飞刀","古龙",5.1));
col.add(new Book("三国演义","罗贯中",34.6));
for (Object book:col) {
System.out.println(book);
}
}
}