集合概念
概念:對象的容器,實現了對對象常用的操作,類似數組功能。
和數組的區別:
-
數組長度固定,集合長度不固定
-
數組可以存儲基本類型和引用類型,集合只能存儲引用類型
Collection體系
Collection為該體系的根接口,代表一組對象,成為“集合”;
-
List接口的特點:有序,有下標、元素可重復
-
ArrayList
-
LinkedList
-
Vector
-
-
Set接口的特點:無序,無下標、元素不可重復
-
HashSet
-
SortedSet
-
TreeSet
-
-
Collection的使用
-
添加與刪除元素
public class Demo1 {
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);
//清空
collection.clear();
}
}
-
遍歷元素與判斷
public class Demo1 {
public static void main(String[] args) {
//創建集合
Collection collection = new ArrayList();
//遍歷元素[重點]
//1、使用增強for
for (Object object : collection) {
System.out.println(object);
}
//2、使用迭代器(專門用於遍歷集合的一種方式)
//hasNext();有無下一個元素
//next();獲取下一個元素
//remove();刪除當前元素
Iterator it = collection.iterator();
while (it.hasNext()){
String s = (String) it.next();
System.out.println(s);
//迭代過程中不能使用刪除方法刪除Collection中的元素(不能並發修改)
//it.remove();//可以刪除迭代器對象的元素
}
//判斷
System.out.println(collection.contains("西瓜"));
System.out.println(collection.isEmpty());
}
}
-
對於對象的操作
//學生類
public 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;
}