-
-
常用方法:
-
boolean add(Object obj) //添加一个对象
-
boolean addAll(Collection c) //将一个集合中的所有对象添加到此集合中
-
void clear() //清空此集合中的所有对象
-
boolean contains(Object o) //检查此集合中是否包含o对象
-
boolean equals(Object o) //比较此集合是否与指定对象相等
-
boolean isEmpty() //判断此集合是否为空
-
boolean remove(Object o) //返回此集合中的元素个数
-
Object[] toArray() //将此集合转换成数组
-
public class HelloWorld { public static void main(String[] args) { //创建集合 Collection collection = new ArrayList(); //添加元素 collection.add("苹果"); collection.add("榴莲"); collection.add("香蕉"); System.out.println(collection.size()); System.out.println(collection); //删除元素 collection.remove("榴莲"); System.out.println(collection.size()); System.out.println(collection); //遍历元素(重点) //1.增强for for (Object object:collection){ System.out.println(object); } System.out.println("-------------------------------"); //2.使用迭代器(专门用来遍历集合) //hasNext() 有没有下一个元素 //next() 获取下一个元素 //remove() 删除当前元素 Iterator iterator = collection.iterator(); while (iterator.hasNext()){ String next = (String) iterator.next(); System.out.println(next); //不能使用Collection删除方法 iterator.remove(); } System.out.println(collection.size()); //判断 System.out.println(collection.contains("西瓜")); System.out.println(collection.isEmpty()); } }
/** * Collection的使用:保存学生信息 */ public class HelloWorld { public static void main(String[] args) { //新建一Collection对象 Collection collection = new ArrayList(); Student s1 = new Student("a",10); Student s2 = new Student("b",20); Student s3 = new Student("c",30); //1.添加数据 //添加的是三个对象的地址 collection.add(s1); collection.add(s2); collection.add(s3); collection.add(s3); System.out.println(collection.size()); System.out.println(collection.toString()); System.out.println("-------------------------------------------------"); //2.删除 //只是把对象从集合中移除,三个对象并没有消失 删除的是对象的指针 // collection.remove(s1); // collection.remove(new Student("a",10)); // collection.clear(); System.out.println(collection.size()); //遍历 //1.增强for for (Object o:collection){ Student s = (Student) o; System.out.println(s.toString()); } System.out.println("-------------------------------------------------"); //2.迭代器 不能使用collection原有的一些操作集合的方法 Iterator iterator = collection.iterator(); while (iterator.hasNext()){ Student student = (Student) iterator.next(); System.out.println(student.toString()); } //判断 System.out.println(collection.contains(s1)); //true // System.out.println(collection.contains(new Student("a",10))); //false System.out.println(collection.isEmpty()); } }