==, .equals(), compareTo(), and compare() (之一)
来源:互联网 发布:java 编译器api 编辑:程序博客网 时间:2024/05/17 10:54
Equality comparison: One way for primitives, Four ways for objects
相等比较:一种是基本,其他四种是对象的
a == b
, a != b
Equal valuesCompares 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/ACompares 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't trivial; 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]
a.compareTo(b)
N/AComparable 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/AComparator 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 assort()
or for use by sorting data structures such as TreeMap and TreeSet. You might want to create a Comparator object for the following.- Multiple comparisions. To provide several different ways to sort somthing. 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()
method. - 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 Strategey 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 referenceto 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.
只有当name引用了同样的对象"Mickey Mouse"所引用的时,这个才是true。假如字符串name从输入或者计算(将字符串合起来后者截取)读取的话,这个判断就是false, 即使name确实有完全相同的字符,许多类定义equals()方法比较对象的值。
Comparing Object values with the equals()
Method---使用equals()方法比较对象值
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 refererences.
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.
因为equals()方法首先使用==测试,它相当的快,当对象是相同的。只有在两个引用不是相同的时候,它才比较values。
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 theComparable<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 a.compareTo(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 plausibiliby.
Other comparison methods
String has the specialized equalsIgnoreCase()
and compareToIgnoreCase()
. String also supplies the constantString.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 thesame object , orequals()
to see if they may be a different object, but have the same value . This kind of error can be very hard to find.
- ==, .equals(), compareTo(), and compare() (之一)
- ==, .equals(), compareTo(), and compare() (之一)
- Java中的equals(),==,compareTo()和compare()
- Java中的equals(),==,compareTo()和compare()
- 【转】java ==、equals、compareTo、compare、sort在比较上的应用
- == equals compareTo 区别
- Java compareTo, equals and hashcode
- compareTo与equals与==
- compareTo, compareToIgnoreCase,equals,==用法
- Java_tips1:compareto(),equals()和==区别
- compareTo与equals与==
- hashcode、equals和compareTo、compare方法的意义及作用
- equals == 和compare to
- 关于 compareTo() , equals,和==使用上的区别
- 2014/03/13 关于“= =”;“compareTo”;“equals”的区别
- equals(),equalsIgnoreCase().compareTo()以及==de 的区别
- 比较compareTo与equals及==的区别
- Java中equals()、==、compareTo()的区别
- universal image loader使用详解一
- 给Ubuntu 13.04换源 软件源、更新源
- 如何卸载eclipse中的ADT
- 数据可视化 D3.js实现力导向图之二(node带文字说明和提示)
- Codeforces Round #221 (Div. 2) B. I.O.U.
- ==, .equals(), compareTo(), and compare() (之一)
- This Android SDK requires Android Developer Toolkit version 20.0.0 or above
- 率失真优化的几篇论文
- 黑马程序员_1数据类型转换
- 如何完全卸载oracle
- 从郑大到北邮的心路历程
- 在使用MyEclipse新建文件时常常有些不需要的冗余代码可以采用如下方式进行更改
- 如何在Eclipse开发环境进行android应用调试
- 黑马程序员---Java基础学习之Java语法格式