java集合中提供了为Collection接口和Map接口
两者的不同 Conllection集合存储元素是单一元素,而Map集合是以键值对的形式存储元素
Conllection是接口不能实例化对象,利用多态可以使用它的具体实现子类
常用方法
Boolean add(E e); 添加元素
Boolean remove(Object O) 从集合中移除指定元素
void clear(); 清空集合中的所有元素
Boolean isEmpty() 判断集合是否为空
int size();获得集合的长度,元素的个数
Collection集合的使用
利用多态
Collection<String> c=new ArrayList<String>(); //创建集合对象 String s=”itcast”; c.add(s);//添加元素 c.add(“hello”); Iterator<String> it=c.iterator(); //通过集合对象得到迭代器对象 While(it.hasNext()){ //调用it.hasNext() ,方法判断是否还有元素 String s=it.next(); //通过next方法获取下一个元素 System.out.println(s); }
Collection 集合的遍历
//返回此集合中的迭代器,通过 集合中iterator()方法得到 ,多态的方式
Iterator<String> it=c.iterator();//是ArrayList 的具体实现类
//E next ; 返回迭代器中下一个元素
System.out.println(it.next());
System.out.println(it.next());
//boolean hasNext(); 如果迭代器中有更多的元素,则返回true, 当下一个元素为null时返回false
//
// if(it.hasNext()){
// System.out.println(it.next());
// }
while (it.hasNext()){
String its=it.next();
System.out.println(its);
list 继承Collection接口 本身也是接口
特点
继承Collection集合
具有父类接口方法
查阅API,看List的介绍。有序的 collection(也称为序列)。此接口的用户可以对列表中每个元素的插入位置进行精确地控制。用户可以根据元素的整数索引(在列表中的位置)访问元素,并搜索列表中的元素。与 set 不同,列表通常允许重复的元素。
看完API,我们总结一下:
List接口:
List接口的常用子类有:
//注意索引
Void add(int index,E e); //插入指定元素
E remove(int index) //删除索引出指定元素
E set(int index,E e)//修改指定索引处的元素,返回修改后的元素
E get(int index)//获得索引的元素