特點:代表一組任意類型的對象,無序、無下標、不能重復。
方法:
1.boolean add(Object obj)添加一個對象
2.boolean addAll(Collection c)將一個集合中的所有對象添加到此集合中。
3.void clear()清空此集合中的所有對象。
4.boolean contains 檢查此集合中是否包含o對象
5.boolean equals(Object obj)比較此集合是否與指定對象相等
6.boolean isEmpty 判斷此集合是否為空
7.boolean remove(Object o)在此集合中移除o對象
8.int size 返回此集合中的元素個數
9.Object [] toArray 將此集合轉換為數組
public class Demo01 {
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("蘋果");
//collection.clear();//清空
System.out.println("刪除之后:"+collection.size());
//遍歷元素[重點]
//方法1:增強for(for each)
System.out.println("===========方法1===========");
for (Object object:collection) {
System.out.println(object);
}
//方法2:使用迭代器(迭代器是專門用來遍歷集合的一種方式)
//Iterator的三個方法
//1.hasNext();有沒有下一個元素
//2.next();獲取下一個元素
//3.remove();刪除當前元素
System.out.println("=============方法2for增強============");
Iterator it=collection.iterator();
while (it.hasNext()){
String s=(String) it.next();//強制轉換
System.out.println(s);
//注意:迭代器在迭代過程中不允許用collection的remove方法,否則會報錯;例如:collection.remove(s);
//但是可以使用迭代器的remove方法刪除
//it.remove();
}
System.out.println("元素個數:"+collection.size());
//4.判斷
System.out.println(collection.contains("西瓜"));//判斷此集合中是否包含這個元素,有為true 無為flase
System.out.println(collection.isEmpty());//判斷此集合是否為空,空為true 非空為flase
}
}
public class Demo02 {
public static void main(String[] args) {
//新建Collection對象
Collection collection=new ArrayList();
Student S1= new Student("張三",18);
Student S2= new Student("李四",19);
Student S3= new Student("王五",20);
//1.添加數據
collection.add(S1);
collection.add(S2);
collection.add(S3);
//2.刪除數據
collection.remove(S1);
//collection.remove(new Student("王五",18));
//collection.clear();
//System.out.println("刪除之后:"+collection.size());
//3.遍歷
//1.增強for
System.out.println("------------增強for方法------------");
Iterator it=collection.iterator();
for (Object object:collection) {
Student s=(Student) object;
System.out.println(s.toString());
}
//2.迭代器: hasNext() next() remove() ;迭代過程中不能使用collection的刪除方法
System.out.println("------------迭代器方法------------");
Iterator iterator=collection.iterator();
while (iterator.hasNext()){
Student s=(Student) iterator.next();
System.out.println(s.toString());
}
//4.判斷
System.out.println(collection.contains(S2));
System.out.println(collection.isEmpty());
}
}
浙公網安備 33010602011771號