集合类的特点:提供一种存储空间可变的存储模型,存储的数据容量随时发生改变
集合类体系特点
集合:
一、单列(collection):
1、List(ArayList 、LinkedList)
2、Set(HashSet 、TreeSet)
二、双列
Map(HashMap)
Collection 集合概述和使用
Collection集合的概述
1、是单例集合的顶层接口,它表示一组对象,这些对象也成为Collection的元素
2、JDK奴提供此接口的任何直接实现,它提供更具体地子接口实现
创建Collection集合的对象
1、多态的方式
2、具体的实现类ArrayList
运行结果是:[hello, ,world]
Collection集合的常用方法
其中remove方法,如果要移除的元素在集合中存在多个就使用就近原则
Collection集合的遍历
Collection 集合的遍历
Iterator:迭代器,集合的专用遍历方式
迭代器是在util包下,使用时需要导包
1、Iterator<E>Iterator();返回此集合中元素的迭代器,通过集合的Iterator方法得到
2、迭代器是通过集合Iterator()方法得到的,它是依赖集合而存在
迭代器中常用的方法:
1、E Iterator();返回迭代中的下一个元素
2、boolean hasNext();如果迭代具有更多的元素则返回true;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
Collection<String> a = new ArrayList<String>();
a.add("world");
a.add("hello");
a.add(" ");
a.add("world");
System.out.println(a);
Iterator<String> it = a.iterator();
System.out.println(it.next());
for(int i = 0 ; i < a.size() ; i++) { //运行错误时显示 NoSuchElementException 表示被请求的元素不存在
System.out.println(it.next());
}
方法2:
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
集合使用步骤图解
1、创建集合对象
Collection<String> arr = new ArrayList<String>();
2、添加元素
arr.add("...");
3、遍历集合
Iterator<String> it = arr.iterator(); //获取迭代器对象
while(it.hasNext()){ //判断是否还有元素
System.out.println(it.next());
}