Compares values, if it's defined for this class, as it is for most Java core classes. Compares values. Comparable objects can be used by the Collections sort method and data structures that implicitly sort eg, TreeSet, TreeMap.
Note that equals doesn't define the ordering between objects, which compareTo does. Neither is better, it depends on what functionality your class needs. Matthew Brown. A couple of additions: - There is always an equals method, because it's defined in Object.
You only override it if you want different behaviour from the default which is "are these refencing the same object? You don't always have a compareTo method. Rob Spoor. 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 values with the equals Method Use the equals method to compare object values.
The previous example can be fixed by writing: if name. Defining a Comparator object As described in the table above on compare , you can create Comparators to sort any arbitrary way for any class. If you override equals, you should also override hashCode Overriding hashCode. This kind of error can be very hard to find.
Compares references, not values. You want to know if two references are to the same object. Compares values for equality. Comparable interface. Comparator interface. How to compare strings in Python? How to get sub-strings by using Java substring function. Post navigation Prev Tutorial.
Next Tutorial.
0コメント