java中的 和equalsequals和compareTo的区别

Java: ==, .equals(), compareTo(), and compare()
==, .equals(), compareTo(), and compare()
Equality comparison: One way for primitives, Four ways for objects
Comparison Primitives Objects
a == b, a != bEqual values
Compares references, not values. The use of == with object references is generally limited to the following:
Comparing to see if a reference is null.
Comparing two enum values. This works because there is only
one object for each enum constant.
You want to know if two references are to the same object
a.equals(b) N/A
Compares values for equality. Because this method is defined in the Object class,
from which all other classes are derived, it's automatically defined for every class.
However, it doesn't perform an intelligent comparison for most classes unless
the class overrides it. It has been defined in a meaningful way for
most Java core classes.
If it's not defined for a (user) class, it behaves the same as ==.
It turns out that defining equals() isn'
in fact it's moderately hard to get it right, especially in the
case of subclasses. The best treatment of the issues
is in Horstmann's Core Java Vol 1.
[TODO: Add explanation and example]
<pareTo(b)N/A
Comparable interface. Compares values and returns an int
which tells if the values compare less than, equal, or greater than.
If your class objects have a natural order, implement the Comparable&T& interface
and define this method.
All Java classes that have a natural ordering implement this (String, Double, BigInteger, ...).
compare(a,&b)N/A
Comparator interface.
Compares values of two objects. This is implemented as part of the Comparator&T& interface,
and the typical use is to define one or more small utility classes that implement
this, to pass to methods such as sort() or
for use by sorting data structures such as TreeMap and TreeSet.
You might want to create a Comparator object for the following.
Multiple comparisons. To provide several different ways to sort something. For example,
you might want to sort a Person class by name, ID, age, height, ...
You would define a Comparator for each of these to pass to the sort()
System class. To provide comparison methods for classes that you have no control over. For example,
you could define a Comparator for Strings that compared them by length.
Strategy pattern. To implement a strategy pattern, which is a situation where you
want to represent an algorithm as an object that you can pass as
a parameter, save in a data structure, etc.
If your class objects have one natural sorting order, you may not need this.
Comparing Object references with the == and != Operators
The two operators that can be used with object references are
comparing for equality (==) and
inequality (!=). These operators
compare two values to see if they refer to the same object.
Although this comparison is very fast, it is often not what you want.
Usually you want to know if the objects have the same value,
and not whether two objects are a reference to the same object.
For example,
if (name == "Mickey Mouse")
// Legal, but ALMOST SURELY WRONG
This is true only if name is a reference to the same object that
"Mickey Mouse" refers to. This will be false
if the String in name was read from input or computed (by putting
strings together or taking the substring), even though name
really does have exactly those characters in it.
Many classes (eg, String) define the equals()
method to compare the values of objects.
Comparing Object values with the equals() Method
Use the equals() method to compare object values.
The equals() method returns a boolean value.
The previous example can be fixed by writing:
if (name.equals("Mickey Mouse"))
// Compares values, not references.
Because the equals() method makes a == test first, it can be
fairly fast when the objects are identical. It only compares the values if
the two references are not identical.
Other comparisons - Comparable&T& interface
The equals method and == and != operators
test for equality/inequality, but
do not provide a way to test for relative values.
Some classes (eg, String and other classes with a natural ordering) implement
the Comparable&T& interface, which defines
a compareTo method. You will want to implement Comparable&T& in
your class if you want to use it with Collections.sort() or Arrays.sort() methods.
Defining a Comparator object
As described in the table above on compare(), you can create
Comparators to sort any arbitrary way for any class.
For example, the String class defines the CASE_INSENSITIVE_ORDER comparator.
If you override equals, you should also override hashCode()
Overriding hashCode(). The hashCode()
method of a class is used for hashing in library
data structures such as HashSet and HashMap.
If you override equals(), you should override hashCode()
or your class will not work correctly in these (and some other) data structures.
Shouldn't .equals and .compareTo produce same result?
The general advice is that if a.equals(b) is true, then
<pareTo(b) == 0 should also be true.
Curiously, BigDecimal violates this.
Look at the Java API documentation
for an explanation of the difference.
This seems wrong, although their implementation has some plausibility.
Other comparison methods
String has the specialized equalsIgnoreCase() and compareToIgnoreCase().
String also supplies the constant String.CASE_INSENSITIVE_ORDER Comparator.
The === operator (Doesn't exist - yet?)
Comparing objects is somewhat awkward, so a === operator has been proposed.
One proposal is that
a === b would be the same as ((a == b) || ((a != null) && a.equals(b)))
Common Errors
Using == instead of equals() with Objects
When you want to compare objects, you need to know whether you should
use == to see if they are the same object,
or equals() to see if they may be a different object, but
have the same value. This kind of error can be very
hard to find.
References
Ragenwald's blog entry
and the responses touch on all the equality issues.Java:比较运算符compareTo()、equals()、==之间的区别与应用总结 - hanchuang213的博客 - CSDN博客
Java:比较运算符compareTo()、equals()、==之间的区别与应用总结
equals 方法是 java.lang.Object 类的方法。
有两种用法说明:
(1)对于字符串变量来说,使用“==”和“equals()”方法比较字符串时,其比较方法不同。
“==”比较两个变量本身的&#20540;,即两个对象在内存中的首地址。
“equals()”比较字符串中所包含的内容是否相同。
String s1,s2,s3 = &abc&, s4 =&abc& ;
s1 = new String(&abc&);
s2 = new String(&abc&);
s1==s2& &是 false&&&&& //两个变量的内存地址不一样,也就是说它们指向的对象不&一样,
故不相等。
s1.equals(s2) 是 true&&&&//两个变量的所包含的内容是abc,故相等。
注意(1):
如果:&&&&&&&&& StringBuffer s1 = new StringBuffer(&a&);
&&&&&&&&&&&&&&&&&&&&& StringBuffer s2 = new StringBuffer(&a&);
&&&&&&&&&&&&&&&&&&&&&&
结果:&&&&&&&&&& s1.equals(s2)& //是false
解释:StringBuffer类中没有重新定义equals这个方法,因此这个方法就来自Object类,
&&&&&&&&&&&
&&&&&&&&& 而Object类中的equals方法是用来比较“地址”的,所以等于false.
注意(2):
对于s3和s4来说,有一点不一样要引起注意,由于s3和s4是两个字符
串常量所生成的变量,其中所存放的内存地址是相等的,
所以s3==s4是true(即使没有s3=s4这样一个赋&#20540;语句)
(2)对于非字符串变量来说,&==&和&equals&方法的作用是相同的都是用来比较其
对象在堆内存的首地址,即用来比较两个引用变量是否指向同一个对象。
&&&&& A obj1&& =&&&new& A();
&&&&& A obj2&& =& &new& A();
那么:obj1==obj2是false
&&&&&&&&&&& obj1.equals(obj2)是false
但是如加上这样一句:obj1=obj2;
那么& obj1==obj2& 是true
&&&&&&&&& obj1.equals(obj2) 是true
总之:equals方法对于字符串来说是比较内容的,而对于非字符串来说是比较
其指向的对象是否相同的。
&&&&&&&&&&&& == 比较符也是比较指向的对象是否相同的也就是对象在对内存中的的首地址。
String类中重新定义了equals这个方法,而且比较的是&#20540;,而不是地址。所以是true。
关于equals与==的区别从以下几个方面来说:&
(1) 如果是基本类型比较,那么只能用==来比较,不能用equals&
public class TestEquals {&
public static void main(String[] args)&
int a = 3;&
int b = 4;&
int c = 3;&
System.out.println(a == b);//结果是false&
System.out.println(a == c);//结果是true&
System.out.println(a.equals(c));//错误,编译不能通过,equals方法&
//不能运用与基本类型的比较&
(2) 对于基本类型的包装类型,比如Boolean、Character、Byte、Shot、Integer、Long、Float、Double等的引用变量,==是比较地址的,而equals是比较内容的。比如:&
public class TestEquals {&
public static void main(String[] args)&
{ Integer n1 = new Integer(30);&
Integer n2 = new Integer(30);&
Integer n3 = new Integer(31);&
System.out.println(n1 == n2);//结果是false 两个不同的Integer对象,故其地址不同,&
System.out.println(n1 == n3);//那么不管是new Integer(30)还是new Integer(31) 结果都显示false&
System.out.println(n1.equals(n2));//结果是true 根据jdk文档中的说明,n1与n2指向的对象中的内容是相等的,都是30,故equals比较后结果是true&
System.out.println(n1.equals(n3));//结果是false 因对象内容不一样,一个是30一个是31&
这是Integer的实例,如果是其他的比如Double、Character、Float等也一样。
(3) 注意:对于String(字符串)、StringBuffer(线程安全的可变字符序列)、StringBuilder(可变字符序列)这三个类作进一步的说明。&
(a)首先,介绍String的用法,请看下面的实例:&
public class TestEquals {&
public static void main(String[] args) {&
String s1 = &123&;&
String s2 = &123&;&
String s3 = &abc&;&
String s4 = new String(&123&);&
String s5 = new String(&123&);&
String s6 = new String(&abc&);&
System.out.println(s1 == s2);//(1)true&
System.out.println(s1.equals(s2));//(2)true&
System.out.println(s1 == s3);//(3)flase&
System.out.println(s1.equals(s3));//(4)flase&
System.out.println(s4 == s5);//(5)flase&
System.out.println(s4.equals(s5));//(6)true&
System.out.println(s4 == s6);//(7)flase&
System.out.println(s4.equals(s6));//(8)flase&
System.out.println(s1 == s4);//(9)false&
System.out.println(s1.equals(s4));//(10)true&
答案解释:s1与s2分别指向由字符串常量”123” 创建的对象,在常量池中,只有一个对象,内容为123,有两个引用s1和s2指向这个对象,故这两个引用变量所指向的地址是相同的,因而(1)处的运行结果为true,又因为s1.equals(s2)是比较s1和s2所指向的对象的内容是否相等,而我们知道这两个对象的内容都是字符串常量”123”,故标记(2)处的运行结果是true。
用同样的方法分析,s1和s3所指向的对象不一样,内容也不一样,故标记(3)和(4)处运行结果是false。&
再看看s4和s5,这两个引用变量所指向的对象的内容都是一样的(内容都是123),但是这两个对象是用new操作符创建处类的,是在内存中分配两块空间给这两个对象的,因而这两个对象的内存地址不一样,故事两个不同的对象,标记(5)处的s4 == s5 运行结果为false,但是内容一样,故标记(6)处的s4.equals(s5)运行结果为true。同理,s4和s6所指向的对象地址不同,内容也不相同。故标记(7)(8)处运行结果为false。&
s1和s4分别指向两个不同的对象(之所以这样称呼,是因为这两个对象在内存中的地址不相同,故而对象不相同),故标记为(9)处的s1 == s4运行结果为false,而标记为(10)处的s1.equals(s4)运行结果为true.
(4) 再看一种情况,先看一个例子(该例子是Java编程思想第三章的例子):&
class Value&
public class EqualsMethod2 {&
public static void main(String[] args) {&
Value v1 = new Value();&
Value v2 = new Value();&
v1.i = v2.i = 100;&
System.out.println(v1.equals(v2));//(1)flase&
System.out.println(v1 == v2);//(2)true&
运行结果疑问:乍一看结果,有点惊讶,为什么不是true呢,不是说equals方法是比较内容的吗?&
解释:不错,如果在新类中被覆盖了equals方法,就可以用来比较内容的。但是在上面的例子中类Value并没有覆盖Object中的equals方法,而是继承了该方法,因此它就是被用来比较地址的,又v1和v2的所指向的对象不相同,故标记(1)处的v1.equals(v2)运行结果为false,标记为(2)处的v1 == v2运行结果也为false。&
总结:equals和==的介绍就到此处,如果有更好的或者更新的解释请大家多多指教,谢谢。
1、== 和 equals的区别:
&==主要是两个变量&#20540;的比较,返回&#20540;为true 或者是false。
对于普通变量,如:int a=10; int &b= 10; a==b,返回为 true。
而对于下面情况:
&&& String &a=new String(&abc&);
&&& String &b=new String(&abc&);
a==b; 返回的则是一个false。这是因为,对于对象的比较是对对象引用的比较,对于a和b ,他们在内存中对应的地址是不一样的,所以a==b 返回的&#20540;是一个false.
==操作符并不涉及对象内容的比较。若要对对象内容进行比较,则用equals. 如果 在本例中,a.equals(b)则返回是一个true&#20540;。
总而言之,==是对对象地址的比较,而equals是对对象内容的比较。对于基本数据类型,一般用==,而对于字符串的比较,一般用equals
2、对于compareTo(), 在API中,.lang包下面的基本数据类型的封装类都提供了该方法,如 Integer,Float,Byte,Short,Character
在基本数据中,compareTo()是比较两个Character 对象;
在 Boolean中,是用boolean的实例于其它实例进行比较;
在String 中,则是按照字典顺序进行比较,返回的&#20540;是一个int 型。
贴一段代码
public class Test{
&& public static void main(String args[]){
&& &String s1=new String(&abc&);
&& &String s2=new String(&abc&);
&& &System.out.println((s1==s2)? &true&:&false&);
&& &System.out.println((s1.equals(s2))? &true&:&false&);
&& &pareTo(s2)==0){
&& &System.out.println(&s1 is equal s2&);}
&& &s1=s2;
&& &System.out.println((s1==s2)? &true&:&false&);
程序的运行结果为:
s1 is equals s2
这里需要说明的一点,s2对象赋&#20540;给s1之后,s2和s1的引用其实是指向了内存中的同一个位置。所以,再进行比较时,就是true.
我的热门文章hashCode()、equals()以及compareTo()方法的理解
判断两个对象是否相等(是同一个对象),首先调用hashCode()方法得到各自的hashcode,
1、如果hashcode不相等,则表明两个对象不相等。
2、如果hashcode相等,继续调用equals方法进行判断
& 2.1:equals()返回true,则对象相等
& 2.2:equals()返回fasle,两对象不相等
所以,要求程序员在重写hashCode方法时尽量做到:不一样的对象,hashCode不一样,这样在判断两个对象是否是同一对象时可以提高效率。
根据这两点,我们可以看一道常见的JAVA面试题:
题目:对于两个对象A、B,A.equals(B)==true,不一定有相同的hashCode(); 这句话是错误的。
当然你自己定义的对象可以实现equals相同而hashCode不同(并不会报错,不知道JAVA为什么不限死),但java的Object类中规定相同的对象一定要有相同的hashCode:原话如下:
Note that it is generally necessary to
override the hashCode method whenever this method is
overridden, so as to maintain the general contract for the
hashCode method, which states that equal objects must have
equal hash codes.
compareTo()方法和equals()方法的关系:
对于某些对象如集合(TreeSet)需要实现内部排序,所以要实现Comparable接口,从而要实现里面的唯一方法compareTo();实现Comparable接口的对象表明遵循自然排序。从Comparable的API中可以看出:
&重写compareTo()方法,不要求必须重写equals()方法,但是却强烈推荐重写equals(),以使两个方法的比较结果在逻辑上是一致。原话如下:
It is strongly recommended (though not
required) that natural orderings be consistent with equals. This is
so because sorted sets (and sorted maps) without explicit
comparators behave "strangely" when they are used with elements (or
keys) whose natural ordering is inconsistent with equals. In
particular, such a sorted set (or sorted map) violates the general
contract for set (or map), which is defined in terms of the
equals method.
所以在编写需要用TreeSet添加的对象时,该对象一定要实现Comparable接口,并且重写compareTo()方法,并推荐同时重写equals()方法
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。大多转载自 百度知道,个人整理以便日后阅读。
pareTo(value2) == 0
value1.equals(value2)
equals的效率高些,compareTo其实就是按照编码的数&#20540;求差&#20540;,根据差&#20540;进行比较,它能确定两个String在字典顺序上的前后性,当你只是想知道是否一致时,用equals也行,效果一样。
另外,equals是Object的方法,要求涉及到比较操作的继承类要自己重写该方法,所以String重写了equals,而compareTo为String的方法。所以:
pareTo(value2),当value1不为String类型时,会报错。
value1.equals(value2),都会进行比较。
实现了Comparable接口的类才有compareTo方法,有了就可以用,
所有已知实现类:
Authenticator.RequestorType, BigDecimal, BigInteger, Boolean, Byte, ByteBuffer, Calendar, Character, CharBuffer, Charset, ClientInfoStatus, CollationKey, Component.BaselineResizeBehavior, CompositeName, CompoundName, Date, Date, Desktop.Action,String .....很多~
但是Object类 只有.equals(),没compareTo
Object是根类,它有的方法,其他类都可以继承,使用.所以.equals 基本随时能用.
* 实现Comparable接口,重写compareTo方法,返回值1,0,-1
* 覆写compareTo方法就是重建排序规则
public int compareTo(Object obj) {
Person p = (Person)
if (p.score & this.score) {
} else if (p.score & this.score) {
return -1;
// 如果成绩相等则判断年龄
if (p.age & this.age) {
} else if (p.age & this.age) {
return -1;
: 基本都用这个比较,
Java里面包含8个基本,分别是:
boolean、byte、char、short、int、float、double、long
注意String 可不属于基本数据类型,它是个类...
2..equals() 用于引用数据类型(除了上面的8个,都是引用数据类型,包括封装类,Object子类等),
比较是否指向相同的对象,
例如 String str = &abc&;
等效于: char data[] = {'a', 'b', 'c'};
String str = new String(data);
就是str 指向了
new String(data) 这个对象. 如果再有其他变量也指向这个对象,他们比较的结果就返回
由于此方法在Object里, 所以它有很多重写, 具体要看说明;
另外``` equalsIgnoreCase()可以忽略大小写;&
Object和String的equals()实现存在区别,所以上面的例子不太友好。有demo在最后
3. compareTO可以比较两个字符串并且得到顺序.
按字典顺序比较两个字符串。该比较基于字符串中各个字符的 Unicode &#20540;。将此 String 对象表示的字符序列与参数字符串所表示的字符序列进行比较。
String类 equals和compareTo源码分析:
public boolean equals(Object anObject) {
  if (this == anObject) {
  if (anObject instanceof String) {
  String anotherString = (String)anO
  int n =
  if (n == anotherString.count) {
  char v1[] =
  char v2[] = anotherString.
  int i =
  int j = anotherString.
  while (n-- != 0) {
  if (v1[i++] != v2[j++])
  public int compareTo(String anotherString) {
  int len1 =
  int len2 = anotherString.
  int n = Math.min(len1, len2);
  char v1[] =
  char v2[] = anotherString.
  int i =
  int j = anotherString.
  if (i == j) {
  int k =
  int lim = n +
  while (k & lim) {
  char c1 = v1[k];
  char c2 = v2[k];
  if (c1 != c2) {
  return c1 - c2;
  } else {
  while (n-- != 0) {
  char c1 = v1[i++];
  char c2 = v2[j++];
  if (c1 != c2) {
  return c1 - c2;
  return len1 - len2;
object 的默认equals实现:
public boolean equals( Object o2 )
this == o2;
Views(...) Comments()

我要回帖

更多关于 java中equals 的文章

 

随机推荐