概念:对象的容器,实现了对对象常用的操作,类似数组功能。
和数组的区别:
数组长度固定,集合长度不固定
数组可以存储基本类型和引用类型,集合只能存储引用类型
Collection为该体系的根接口,代表一组对象,成为“集合”;
List接口的特点:有序,有下标、元素可重复
ArrayList
LinkedList
Vector
Set接口的特点:无序,无下标、元素不可重复
HashSet
SortedSet
TreeSet
添加与删除元素
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; } @Override public String toString() { return "Student[" + "name='" + name + '\'' + ", age=" + age + ']'; } } public class Demo1 { 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()); //删除 // collection.remove(s1); // collection.clear(); // System.out.println("删除之后:"+collection.size()); //遍历 for (Object o : collection) { Student s = (Student) o; System.out.println(s.toString()); } System.out.println("------------"); Iterator it = collection.iterator(); while (it.hasNext()){ Student s = (Student) it.next(); System.out.println(s.toString()); } //判断 System.out.println(collection.contains(s1)); System.out.println(collection.isEmpty()); } }