Collection的使用

Interface Collection:Collection是个接口
用接口的引用指向实现类对象

 //以多态的形式创建集合对象,调用单例集合中的共有方法
        Collection<String> collection= new ArrayList<>();

Collection的常用方法:

方法描述
add​(E e)确保此集合包含指定的元素
clear​()从此集合中删除所有元素
contains​(Object o)如果此集合包含指定的元素,则返回 true
isEmpty​()如果此集合不包含元素,则返回 true
remove​(Object o)从该集合中删除指定元素的单个实例(如果存在)
int size​()返回此集合中的元素数
public class CollectionTest1 {
   public static void main(String[] args) {
       //以多态的形式创建集合对象,调用单例集合中的共有方法
       Collection<String> collection= new ArrayList<>();
       collection.add("张三");
       collection.add("李四");
       collection.add("王五");

       System.out.println(collection.isEmpty());
       System.out.println(collection);
       System.out.println("-------------------");

       //remove这里要注意,再根据对象做删除的时候,得重写equals方法
       //如果没有重写,因为equals比较的是地址,就无法删除
       Collection<Student> c=new ArrayList<>();
       c.add(new Student("张三",18));
       c.add(new Student("李四",22));
       c.add(new Student("王五",25));
       c.remove(new Student("李四",22));
       System.out.println(c);
       collection.remove("李四");
       System.out.println(collection);
       System.out.println("-------------------------");
       collection.clear();

       System.out.println(collection);

   }
}

Student类:

 //没沾全,右键generate自动生成
public class Student {
    private String name;
    private int age;

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

未重写equals方法的结果:

false
[张三, 李四, 王五]
-------------------
[Student{name = 张三, age = 18}, Student{name = 李四, age = 22}, Student{name = 王五, age = 25}]
[张三, 王五]
-------------------------
[]

重写equals方法的结果:

false
[张三, 李四, 王五]
-------------------
[Student{name = 张三, age = 18}, Student{name = 王五, age = 25}]
[张三, 王五]
-------------------------
[]

contains方法在这同理,如果没有重写equals方法,返回结果就不同,remove和contains方法底层都依赖于equals方法来进行操作。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值