单列集合:一次添加一个元素(Collection接口)
注意:这里的Collection接口,指的是List 和 Set接口所共有的方法
import java.util.ArrayList; import java.util.Collection; public class CollectionTest1 { public static void main(String[] args){ // 使用多态的形式创建集合对象,调用集合中的共有方法:接口的引用指向实现类的对象 // 左边是编译类型,右边是运行类型(左边的编译类型决定调用哪些属性和方法,右边的运行类型决定具体实现哪些内容) Collection<String> c = new ArrayList<>(); // public boolean add(E e):把给定的对象添加到当前集合中 c.add("张三"); c.add("李四"); System.out.println(c); // public boolean remove(E e):把给定的对象在当前集合中删除 c.remove("李四"); System.out.println(c); // public void clear():清空集合中所有的元素 c.clear(); System.out.println(c); // public boolean isEmpty():判断当前集合是否为空(这里只是判断集合中是否有元素,无法判断集合是否为null) System.out.println(c.isEmpty()); // public boolean contains(E e):判断当前集合中是否包含给定的对象 c.add("张三"); c.add("李四"); System.out.println(c.contains("张三")); // public int size():返回集合中元素的个数 System.out.println(c.size()); } }
集合的通用遍历方式:迭代器、for循环、foreach方法
Student类
package domain; public class Student { private String name; private int 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; } public Student(String name, int age){ this.name = name; this.age = age; } }
package collection; import domain.Student; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class CollectionTest2 { public static void main(String[] args){ Collection<Student> c = new ArrayList<>(); c.add(new Student("张三", 23)); c.add(new Student("李四", 24)); c.add(new Student("王五", 25)); // 1.迭代器遍历 System.out.println("=================迭代器遍历=================="); // Iterator<E> iterator():获取遍历集合的迭代器对象 Iterator<Student> it = c.iterator(); // boolean hasNext():判断集合中是否还有下一个元素 while(it.hasNext()){ // E next():获取集合中的下一个元素 Student s = it.next(); System.out.println(s.getName() + "," + s.getAge()); } } }
package collection; import domain.Student; import java.util.ArrayList; import java.util.Collection; public class CollectionTest3 { public static void main(String[] args){ Collection<Student> c = new ArrayList<>(); c.add(new Student("张三", 23)); c.add(new Student("李四", 24)); c.add(new Student("王五", 25)); // 2.增强for循环遍历 System.out.println("=================增强for循环遍历=================="); for(Student stu:c){ System.out.println(stu.getName() + "," + stu.getAge()); } } }
package collection; import domain.Student; import java.util.ArrayList; import java.util.Collection; public class CollectionTest4 { public static void main(String[] args){ Collection<Student> c = new ArrayList<>(); c.add(new Student("张三", 23)); c.add(new Student("李四", 24)); c.add(new Student("王五", 25)); // 3.foreach循环遍历 System.out.println("=================foreach循环遍历=================="); c.forEach(stu -> System.out.println(stu.getName() + "," + stu.getAge())); } }
标签:进阶,28,System,println,add,Student,集合,new,public From: https://www.cnblogs.com/REN-Murphy/p/17984708