在java中使用contains()方法 [英] Using contains() method in java
本文介绍了在java中使用contains()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用contains()来检查我试图插入Arraylist的元素是否已存在吗?
protected void addTeacher(Teacher t){
if(!(teacherList.contains(t)))
teacherList.add(t);
}
谢谢!
我的尝试:
搜索与编码相关的网站中的具体示例
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);
}
Thanks!
What I have tried:
Searching concrete examples in websites related to coding
推荐答案
Quote:
搜索与编码相关的网站中的具体例子
Searching concrete examples in websites related to coding
你应该学会自己使用谷歌。
这里是第一个回答: Java.lang.String.contains()方法示例 [ ^ ]
使用时要记住的重要事项像这样的方法包含()
,indexOf()
这些方法依赖于使用equals()
比较对象类型的方法。
在您的方案中,您正在尝试查看列表是否包含实例教师
,因此您可能需要考虑重写equals()
方法以检查对象中是否相等。 此页面 [ ^ ]有一个很好的描述。
An important thing to remember when using methods likecontains()
,indexOf()
is that these sort of methods rely on using theequals()
method to compare object types.
In your scenario, you're trying to see whether a list contains an instance ofTeacher
, so you may need to consider overriding theequals()
method to check for equality in the objects. This page[^] has a good description.
这篇关于在java中使用contains()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文