集合
collection集合概述
是单例集合的顶层接口,它表示一组对象
JDK不提供此类集合的直接使用实现,它提供更具体的子接口(如set和list)实现
创建collection集合的对象
多态的方式,具体实现类Arraylist等
代码实例:
Collection<String> co = new ArrayList<String>();
co.add("hello");
co.add("hahah");
co.remove("hello");
// co.clear();
System.out.println(co.isEmpty());
System.out.println(co.size());
// System.out.println(co.add("hello"));
System.out.println(co);
集合的遍历
迭代器:Iterator;集合专用的遍历方法
.next方法可以获取集合的下一个元素;
hasNext方法,确认集合中是否有下一个元素;
可以用此方法+while遍历集合
上代码:
Iterator<String> it = co.iterator();//得到迭代器
while(it.hasNext()){
//如果集合中还有下一个元素就执行
String s = it.next();//获取下一个元素
System.out.println(s);
学生对象的实例
创建学生类
package collectiondemo;
public class student {
private String name;
private int age;
public student(){
};
public student(String name, int age){
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
创建并遍历学生集合
package collectiondemo;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class demo {
public static void main(String[] args) {
Collection<student> c = new ArrayList<student>();
student s1 = new student("haha",20);
student s2 = new student("yoyo",20);
c.add(s1);
c.add(s2);
Iterator<student> it = c.iterator();
while (it.hasNext()){
student s =it.next();
System.out.println(s.getName()+","+s.getAge());
}
}
}