Collection 的概述和使用
collection需要新建一个对象
Collection<String> c =new ArrayList<String>();//存储string类型 //实例化
插入
//添加元素add(); c.add("hello"); c.add("world"); c.add("java"); System.out.println(c);
常用方法
add();插入元素
boolean remove();移除集合中制定元素
成功返回true
失败返回false
System.out.println(c.remove("hello"));
clear();清空集合中元素
c.clear();
System.out.println(c.isEmpty());
返回true;
boolean contains();判断集合中是否存在指定元素
System.out.println(c.contains("world"));
boolean isEmpty();判断集合中是否存在元素
size ();集合的长度
collection的遍历
Iterator<String> it =c.iterator() ;
获取元素前应该进行判断
if(it.hasNext()){ System.out.println(it.next()); }
用循环改进
while(it.hasNext()){ System.out.println(it.next()); }
while(it.hasNext()){ String s=it.next(); System.out.println(s); }
示例 使用collection存储学生对象
import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Collection; import java.util.ArrayList; //定义学生类 //创建collection对象 //创建学生对象 //把学生添加到集合 public class collectiondemo { public static void main(String[] args) { Collection<Student> c=new ArrayList<Student>(); Student s1=new Student("1",19); Student s2=new Student("2",18); Student s3=new Student("3",20); c.add(s1); c.add(s2); c.add(s3); //遍历集合 Iterator<Student> it =c.iterator(); while(it.hasNext()){ Student s=it.next(); System.out.println(s.getName()+s.getAge()); } } } class Student { private String name; private int age; 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; } }
原文:https://www.cnblogs.com/sjyoops/p/14774143.html