Collection接口的使用 保存学生信息

package com.oop.collection;

import lombok.Data;

/**
 * @Author: cg
 * @Date: 2020/12/20/14:36
 * @Description:
 */
@Data
public class Student {
    
    
    private String name;
    private int age;
    public Student(){
    
    }

    public Student(String name, int age) {
    
    
        super();
        this.name = name;
        this.age = age;
    }
}

package com.oop.collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @Author: cg
 * @Date: 2020/12/20/14:35
 * @Description: Collection接口的使用 保存学生信息
 */
public class Demo2 {
    
    
    public static void main(String[] args) {
    
    
        //新建Collection对象
        Collection collection = new ArrayList();
        Student s1 = new Student("张三", 20);
        Student s2 = new Student("李四", 18);
        Student s3 = new Student("王五", 22);
        //1、添加数据
        collection.add(s1);
        collection.add(s2);
        collection.add(s3);
        System.out.println("元素个数:" + collection.size());
        System.out.println(collection.toString());
        //2、删除
//        collection.remove(s1);
//        collection.clear();
//        System.out.println("删除之后:" + collection.size());
        //3、遍历
        //3.1使用增强for
        System.out.println("------3.1使用增强for-------");
        for (Object object : collection) {
    
    
            Student s = (Student)object;
            System.out.println(s.toString());
        }
        //3.2使用迭代器(迭代器:专门用来遍历集合的一种方式)
        //hasNext();有没有下一个元素
        //next();获取下一个元素
        //remove();删除当前元素
        System.out.println("------3.2使用迭代器-------");
        Iterator it = collection.iterator();
        while (it.hasNext()){
    
    
            Student s = (Student) it.next();
            System.out.println(s.toString());
            //System.out.println("元素个数:" + collection.size());
        }
        //4、判断
        System.out.println(collection.contains(s1));
        System.out.println(collection.isEmpty());
    }
}

猜你喜欢

转载自blog.csdn.net/m0_49162312/article/details/111430143
今日推荐