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());
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值