【Java】contains 和 equals的区别
来源:互联网 发布:冰川网络收购 编辑:程序博客网 时间:2024/06/18 14:45
一, contains的作用:
如果集合中包含有特定的元素(也是就是参数),如果包含的话返回true
contains
boolean contains(Object o)
Returns true if this collection contains the specified element. More formally, returnstrue if and only if this collection contains at least one element e such that(o==null ? e==null : o.equals(e)).- 参数:
o
- element whose presence in this collection is to be tested- 返回:
- true if this collection contains the specified element
- 抛出:
ClassCastException
- if the type of the specified element is incompatible with this collection (optional)NullPointerException
- if the specified element is null and this collection does not permit null elements (optional)
二,equals的作用:
用于String类型的对比,且当不为null,类型为char,string的数据类型比较,正确返回true;
注意:如果两个对象x和y满足x.equals(y) == true,它们的哈希码(hash code)则相同。Java对于eqauls方法和hashCode方法是这样规定的:(1)如果两个对象相同(equals方法返回true),那么它们的hashCode值一定要相同;(2)如果两个对象的hashCode相同,它们并不一定相同。
equals方法必须满足自反性(x.equals(x)必须返回true)、对称性(x.equals(y)返回true时,y.equals(x)也必须返回true)、传递性(x.equals(y)和y.equals(z)都返回true时,x.equals(z)也必须返回true)和一致性(当x和y引用的对象信息没有被修改时,多次调用x.equals(y)应该得到同样的返回值),而且对于任何非null值的引用x,x.equals(null)必须返回false。
实现高质量的equals方法的诀窍包括:1. 使用==操作符检查”参数是否为这个对象的引用”;2. 使用instanceof操作符检查”参数是否为正确的类型”;3. 对于类中的关键属性,检查参数传入对象的属性是否与之相匹配;4. 编写完equals方法后,问自己它是否满足对称性、传递性、一致性;5. 重写equals时总是要重写hashCode;6. 不要将equals方法参数中的Object对象替换为其他的类型,在重写时不要忘掉@Override注解。
本段参考:http://www.importnew.com/22083.html
equals
public boolean equals(Object anObject)
Compares this string to the specified object. The result istrue
if and only if the argument is notnull
and is aString
object that represents the same sequence of characters as this object.- 重载:
equals
in classObject
- 参数:
anObject
- The object to compare thisString
against- 返回:
true
if the given object represents aString
equivalent to this string,false
otherwise- 另请参见:
compareTo(String)
,equalsIgnoreCase(String)
阅读全文
0 0
- Java中equals()和contains()的区别
- 【Java】contains 和 equals的区别
- java 中的 equals contains的区别实例
- Java中equals和contains理解
- 关于C#的Equals和Contains方法
- java ==和equals、equals和hashCode的区别
- equals和contains
- equals和contains
- Equals和==的区别,java
- java == 和 equals的区别
- 【Java】双等号和equals的区别
- java ==和equals的区别
- java中hashcode和equals的区别
- Java "equals"和"=="的区别
- java:equals 和 ==的区别
- 【Java】双等号和equals的区别
- java中equals和equalsignorecase的区别
- java中的hashcode和equals的区别?
- 重装系统前必做的事情
- 致自己
- oracle游标详细用法
- Hinton Neural Networks课程笔记1c:几种激活函数Linear、Binary、ReLU、Stochastic binary neurons
- 磁盘文件的创建与删除
- 【Java】contains 和 equals的区别
- 接口:
- 有重复元素的排列问题
- 栈和队列经典题目汇总
- tensorflow之变量初始化(tf.Variable)
- C#读取excel的有效行数或者最大有效列数
- poj-1321棋盘问题
- 剖析 epoll ET/LT 触发方式的性能差异误解
- 集合划分问题