找回密码
 注册

QQ登录

快捷登录

新浪微博登陆

搜索
CDD 法语助手
楼主: dxiao2

请教SG的最后一年实习+ 新加soge面试流水帐

46
回复
12076
查看
[ 复制链接 ]

新浪微博达人勋

Equality comparison: One way for primitives, Four ways for objects
Comparison Primitives Objects
a == b, a != bEqual 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/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.
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/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 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.
2007-11-2 14:36:34

使用道具 举报

头像被屏蔽

新浪微博达人勋

提示: 作者被禁止或删除 内容自动屏蔽
2007-10-26 21:03:27
1234
您需要登录后才可以回帖 登录 | 注册 新浪微博登陆

本版积分规则

返回顶部