`

==, .equals(), compareTo(), and compare()[转]

    博客分类:
  • Java
阅读更多
转自[Java Notes]http://leepoint.net/notes-java/data/expressions/22compareobjects.html

==, .equals(), compareTo(), and compare()

Equality comparison: One way for primitives, Four ways for objects

Comparison Primitives Objects
a == b , a != b Equal 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'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/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 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 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 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.

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 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 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.
分享到:
评论

相关推荐

    Comparison_C_code_same_string.rar_Same Same

    `String.Compare()`和`String.Equals()`方法都有接受`CultureInfo`参数的版本,可以指定比较时使用的文化规则。 最后,`StringComparer`类提供了更多的比较选项,如`StringComparer.OrdinalIgnoreCase`和`...

    strcmp函数应用.zip

    在C#中,虽然没有直接对应的strcmp函数,但可以使用string类的CompareTo方法或者String.Compare方法来实现类似的功能。以下是对这两个方法的简要介绍: 1. `CompareTo`方法:这是.NET Framework中String类的一个...

    C# 比较字符串是否相同的源代码

    2. **Compare() 方法**:`System.String`类还提供了一个静态方法`Compare()`,可以进行更复杂的比较。例如,`String.Compare(string1, string2)`会返回一个整数值,表示字符串的相对顺序。如果结果为0,则表示字符串...

    实现元素比较1

    在Java编程中,比较对象是常见的操作,主要涉及到`==`、`equals()`和`compareTo()`这三个方法。理解它们之间的关系对于编写高质量的代码至关重要。 1. `==`、`equals()`、`compareTo()`的关系 `==`用于比较基本...

    compareTo用法

    - 如果两个对象相等(按照`equals`方法判断),则它们的`compareTo`方法应该返回0。 #### 示例应用 假设我们有一个`AutoStudent`对象列表,现在想要根据学生的身高进行升序排序: ```java List&lt;AutoStudent&gt; ...

    学生集合排序

    return s1.getName().compareTo(s2.getName()); } } ``` 最后,我们可以使用`Collections.sort()`方法和自定义的`StudentComparator`对集合进行排序: ```java List&lt;Student&gt; students = ... // 初始化学生集合 ...

    java CompareTo使用案例

    这种设计遵循了“弱有序性”,即如果a.compareTo(b) &gt; 0,那么b.compareTo(a) ,且a.compareTo(b) == 0暗示a.equals(b)也应为true(尽管equals()并不总是要求与compareTo()一致)。 使用`compareTo()`的基本语法: ...

    Android 中英文混合排序

    在"Android 中英文混合排序"这个主题中,我们需要理解如何利用Java(Android的主要编程语言)中的排序机制,结合中文转拼音的方法,来实现这一功能。下面我们将详细探讨这一过程。 首先,Android系统基于Java虚拟机...

    java常用字符串函数集锦

    int compare = s1.compareTo(s2); // compare 将是小于 0 16. indexOf() 和 lastIndexOf() 函数 indexOf() 函数用于查找字符串中的某个字符或子串第一次出现的位置,lastIndexOf() 函数用于查找字符串中的某个...

    java中List对象列表实现去重或取出及排序的方法

    public int compare(Student s1, Student s2) { return s1.getName().compareTo(s2.getName()); } }); ``` 去重和排序List对象列表可以使用多种方法,包括重写equals和hashCode方法,使用HashSet,使用Java 8的...

    C#学习笔记(数据转换)

    字符串比较在C#中有多种方式,主要包括`Compare`、`CompareTo`和`Equals`方法: - **`Compare`**:静态方法,用于比较两个字符串。可以指定是否区分大小写。示例: - `String.Compare(str1, str2)`:比较`str1`与`...

    List数据字段排序不关注数据库,直接排序

    具体做法是创建一个实现了 `Comparator` 接口的类,并在 `compare()` 方法中定义具体的排序逻辑。这里的排序逻辑可以基于对象的任意属性。 #### 示例代码分析 ```java import java.util.Comparator; @...

    JAVA期末考试试题练习.docx

    public int compareTo(MyBook other) { return Double.compare(this.price, other.price); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass()...

    Java软件开发实战 Java基础与案例开发详解 11-3 Set接口实现类 共19页.pdf

    当使用自定义类作为`HashSet`中的元素时,需要重写`hashCode()`和`equals()`方法。这是因为在`HashSet`中,元素的唯一性是由这两个方法决定的。 **Student类示例:** ```java public class Student implements ...

    Java 中比较两个字符串.docx

    在给定的示例中,`stringCompare()` 函数通过逐个字符比较并计算差值来实现字典顺序比较,直到找到不匹配的字符或者遍历完所有字符。如果字符串长度不同,会根据长度差异返回结果。 在实际编程中,根据需求选择合适...

    C#字符串操作

    C#的`String`类提供了多种方法来实现字符串的比较,包括`Compare`、`CompareTo`、`CompareOrdinal`以及`Equals`等。 ##### 1. `Compare` 方法 `Compare`方法用于比较两个字符串对象,它可以灵活地处理大小写敏感性...

    HashMap集合排序

    return Integer.compare(this.speed, other.speed); } else { return this.model.compareTo(other.model); } } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if ...

    c# 字符串的比较算法

    2. **Compare()**:`String.CompareTo()`方法返回一个整数值,表示两个字符串的相对顺序。如果第一个字符串小于第二个,返回负值;如果相等,返回0;如果大于,返回正值。同样有`String.Compare(str1, str2, ...

    复数类的JAVA实现

    由于复数可能涉及到实数域和虚数域的大小比较,因此我们需要定义多个比较方法,如`equals`(检查是否相等)、`compareTo`(比较大小)等: ```java @Override public boolean equals(Object obj) { if (this == ...

    Java源码对用户名进行比较排序.rar

    字符串的比较可以通过`compareTo()`方法或`equals()`方法完成。`compareTo()`方法基于Unicode值比较字符,返回值为负数、零或正数,表示当前字符串小于、等于或大于另一个字符串。`equals()`方法则检查两个字符串...

Global site tag (gtag.js) - Google Analytics