一,collection集合类(需要导包)
它是一个接口,并且collection集合储存的是单列数据
他没有具体的实现类(因为他的实现类也是接口)所以只能通过子类(List,set)的实现类创建对象
二,常用方法
add()添加元素,返回值为boolean
remove()移除指定元素,返回值为boolean
clear()清空集合中的元素,无返回值
contains()判断集合中是否存在指定的元素,返回值为boolean
isEmpty()判断集合是否为空,返回值为boolean
size()集合的长度,返回值为int
三,遍历
collection集合遍历通过迭代器
Iterator<E> __=__.iterator()返回集合的迭代器,通过iterator()方法得到,就像得到迭代器对象
iterator迭代器的方法
next()返回迭代器中的下一个元素,即获取元素
hasNext()如果迭代具有更多元素返回true。即用来判断的
示例:
用collection储存学生对象,然后遍历出学生对象
学生类
public class Student {
public String name;
public String sex;
public int age;
@Override
public String toString(){
return ("姓名:"+name+"\t"+"性别:"+sex+"\t"+"年龄:"+age);
}
public Student(){}
public Student(String name,String sex,int age){
this.name=name;
this.sex=sex;
this.age=age;
}
}
测试类
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class test {
public static void main(String[] args) {
Student s1=new Student("小明","男",21);
Student s2=new Student("小亮","男",22);
Student s3=new Student("小丽","女",21);
Collection c=new ArrayList();
c.add(s1);
c.add(s2);
c.add(s3);
Iterator<Student> sc= c.iterator();
// 死循环方式遍历
// for(int i=0;;i++){
// if(sc.hasNext()){
// System.out.println(sc.next());
// }else{
// break;
// }
// }
while(sc.hasNext()){
System.out.println(sc.next());
}
}
}
结果为