1 、集合框架思维导图
一、什么是集合
存放在java.util.*
。是一个存放对象的容器。
-
存放的是对象的引用,不是对象本身
-
长度不固定
-
只能存放对象
二、collection接口
collection的使用
-
增加元素 add();
-
判断是否包含某个元素 contains();
-
删除某个元素 remove();
-
遍历元素(iterator迭代器)
package com.zheng.demo1; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class MyCollection { public static void main(String[] args) { Collection c = new ArrayList(); //增加元素 c.add("足球"); c.add("篮球球"); c.add("乒乓球"); //集合大小 System.out.println("当前集合大小:" + c.size()); //判断是否包含某个元素 System.out.println(c.contains("足球")); //删除元素 c.remove("足球"); System.out.println("删除一个元素之后大小:" + c.size()); System.out.println("==============="); //打印,增强for循环 for (Object obj : c) { System.out.println("增强for循环取值:"+obj); } System.out.println("=============="); //迭代器形式 Iterator it = c.iterator(); while (it.hasNext()){//判断有无下一个元素 Object obj=it.next();//取值 System.out.println("iterator取值:"+obj); } } }
Iterator:迭代器
-
hasNext(); 查看是否有下一个元素。有为true,无为false
-
next(); 取出下一个元素的值
-
remove(); 删除当前元素
在JAVA中,所有的对象都有toString方法;方便打印
通过添加一个对象到collection集合中
实体类
package com.zheng.demo1; public class Student { private int id; private String name; private String address; public Student() { } public Student(int id, String name, String address) { this.id = id; = name; this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", address='" + address + '\'' + '}'; } }
加入到集合
package com.zheng.demo1; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class MyCollection1 { public static void main(String[] args) { //创建容器 Collection<Student> students = new ArrayList<Student>(); //创建对象 Student student1 = new Student(1, "小明", "北京"); Student student2 = new Student(2, "小红", "河南"); Student student3 = new Student(3, "小黑", "深圳"); Student student4 = new Student(4, "小蓝", "上海"); //添加对象到容器中 students.add(student1); students.add(student2); students.add(student3); students.add(student4); //查看 System.out.println(students.toString()); System.out.println("=========增强for循环输出========="); //增强for循环输出 for (Student student : students) { System.out.println(student.toString()); } System.out.println("=========迭代器输出========="); //迭代器输出 Iterator<Student> iterator = students.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }