Collection体系
什么是集合
- 对象的容器,定义了对多个对象进行操作的常用方法。可以实现数组的功能
- 和数组的区别
- 数组长度固定,集合长度不固定
- 数组可以存储基本类型和引用类型,集合只能存储引用类型
Collection体系
- List接口:有序、有下标、元素可以重复
- Set接口:无序、无下标、元素不可重复
常用方法
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo1 {
public static void main(String[] args) {
Collection collection = new ArrayList();
collection.add("cehncehn");
collection.add("jj");
System.out.println(collection.size());
System.out.println(collection.toString());
for (Object o : collection) {
System.out.println(o);
}
Iterator it = collection.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
System.out.println(collection.contains("jj"));
System.out.println(collection.isEmpty());
}
}
public class Student {
private String name;
private int age;
public Student() {
}
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;
}
@Override
public String toString() {
return "Student [name="+ name + ",age=" + age + "]";
}
}
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo02 {
public static void main(String[] args) {
Collection collection=new ArrayList();
Student s1=new Student("张三",20);
Student s2=new Student("无忌",18);
Student s3=new Student("王二",22);
collection.add(s1);
collection.add(s2);
collection.add(s3);
System.out.println(collection.size());
System.out.println(collection.toString());
Iterator it = collection.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
for (Object o : collection) {
System.out.println(o);
}
}
}