Java集合之Collection
2021-08-24 15:59 young柠檬味 阅读(65) 评论(0) 编辑 收藏 举报概述:
- 是单例集合的顶层接口,他表示一组对象,这些对象也成为Collection的元素
- JDK不提供此接口的任何直接实现,他提供更具体的子接口(如Set和List)实现
创建Collection集合的对象
- 多态的方式
- 具体的实现类ArrayList
1 public class Demo1 { 2 public static void main(String[] args) { 3 Collection<String> list = new ArrayList<>(); 4 list.add("hello"); 5 list.add("world"); 6 list.add("java"); 7 System.out.println(list); 8 } 9 }
注:add方法永远返回true
1 public class Demo2 { 2 public static void main(String[] args) { 3 Collection<String> c = new ArrayList<String>(); 4 c.add("hello"); 5 c.add("world"); 6 c.add("java"); 7 System.out.println(c.remove("java")); 8 c.remove("javaee"); 9 System.out.println(c.contains("hello")); 10 System.out.println(c.isEmpty()); 11 System.out.println(c.size()); 12 c.clear(); 13 System.out.println(c); 14 } 15 }
Iterator:迭代器,集合的专用遍历方式
-
Iterator<E> iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
-
迭代器是通过集合的iterator()方法得到的,所以我们是他是依赖于集合而存在的
Iterator中的常用方法
-
E next():返回迭代中的下一个元素
-
boolean hasNext():如果迭代具有更多元素,则返回true
1 public class IteratorTest { 2 public static void main(String[] args) { 3 Collection<String> c = new ArrayList<String>(); 4 c.add("hello"); 5 c.add("world"); 6 c.add("java"); 7 8 Iterator<String> it = c.iterator(); 9 // String s = it.next(); 10 // System.out.println(s); 11 while (it.hasNext()){ 12 String s1 = it.next(); 13 System.out.println(s1); 14 } 15 } 16 }
1 //学生类 2 public class Student { 3 private String name; 4 private int age; 5 6 public Student(String name, int age) { 7 this.name = name; 8 this.age = age; 9 } 10 11 public Student() { 12 } 13 14 public String getName() { 15 return name; 16 } 17 18 public void setName(String name) { 19 this.name = name; 20 } 21 22 public int getAge() { 23 return age; 24 } 25 26 public void setAge(int age) { 27 this.age = age; 28 } 29 30 public void show() { 31 System.out.println("学生的姓名:" + name + " 学生的年龄:" + age); 32 } 33 } 34 35 36 //测试类 37 public class CollectionTest { 38 public static void main(String[] args) { 39 Scanner sc1 = new Scanner(System.in); 40 System.out.println("请输入要添加学生的数目:"); 41 int num = sc1.nextInt(); 42 Collection<Student> students = addStudent(num); 43 System.out.println(students); 44 bianli(students); 45 } 46 //添加学生对象,2个明确:参数:输入要添加的学生个数;返回值:返回collection集合? 47 public static Collection<Student> addStudent(int num){ 48 Collection<Student> students = new ArrayList<>(); 49 Scanner sc = new Scanner(System.in); 50 for(int i = 0;i<num;i++){ 51 System.out.println("请输入添加的学生的姓名:"); 52 String name = sc.nextLine(); 53 System.out.println("请输入添加的学生的年龄:"); 54 int age = sc.nextInt(); 55 Student s = new Student(name, age); 56 students.add(s); 57 } 58 return students; 59 } 60 61 //遍历学生的collection集合,2个明确:参数,传入collection;返回值:不需要 62 public static void bianli(Collection<Student> s){ 63 Iterator<Student> iterator = s.iterator(); 64 while (iterator.hasNext()){ 65 Student student = iterator.next(); 66 student.show(); 67 } 68 } 69 }