在Java中使用contains()方法 [英] Using contains() method in java

查看:46
本文介绍了在Java中使用contains()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用contains()来检查要插入Arraylist中的元素是否已经存在吗?

Can i use contains() to check if an element i m trying to insert in an Arraylist is already there?

protected void addTeacher(Teacher t){
        if (!(teacherList.contains(t)))
            teacherList.add(t);
    }

我创建了一个教师班.谢谢,

I have created a teacher class. Thanks,

推荐答案

在您的老师类中,您应该覆盖 equals 方法,并为程序定义您的两个对象相等的策略.然后,您可以完美地使用contains方法.

in your Teacher class you should override equals method and define for the program what is your strategy for the equality of two objects. Then you can perfectly use contains method.

请注意,更好的解决方案是使用 Set .

Take note a better solution is to use Set.

a集永远不会在其中保存重复的对象.为了使用你的一套应该覆盖equals和hashCode方法.

a Set never save a duplicate object within it. for using a Set you should override both equals and hashCode methods.

参考此主题,我为其他人清楚地解释了所有类似问题-> 等于和hashCode方法

这篇关于在Java中使用contains()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆