JavaSE框架之Collection集合方法
阿新 • • 發佈:2018-11-17
Collection方法。
1,add(Object o);
2,size();
3,contains();其底層呼叫的是equals方法。
4,toArray();
5,isEmpty();
6,remove();
7,interator();迭代器,含三個方法,
hasNext();
next();
remove();(移除迭代器指向的collection的最後一個元素。)
import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class Test01 { public static void main(String[] args) { Student s1 = new Student("張三", 23); Student s2 = new Student("李四", 23); Student s3 = new Student("王五", 23); Collection collection = new ArrayList(); // 向collection中新增元素 collection.add(s1); collection.add(s2); collection.add(s3); System.out.println("collection的長度為" + collection.size()); System.out.println("collection是否為空" + collection.isEmpty()); System.out.println("collection的" + collection.size()); Object[] array = collection.toArray(); int i = 0; while (i < array.length) { System.out.println("姓名:" + ((Student) array[i]).getName() + ",年齡:" + ((Student) array[i]).getAge()); i++; } System.out.println("collection中是否含有s2" + collection.contains(s2)); System.out.println("---------------------------------"); Iterator iterator = collection.iterator(); while (iterator.hasNext()) { Student next = (Student) iterator.next(); System.out.println("姓名:" + next.getName() + ",年齡:" + next.getAge()); iterator.remove(); } System.out.println("collection中是否含有s2" + collection.contains(s2)); System.out.println("collection是否為空" + collection.isEmpty()); } } class Student { private String name; private int 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; } public Student(String name, int age) { this.name = name; this.age = age; } }