Должны мы всегда переопределять, равняется?

Необходимо удалить компонент миллисекунд из объекта даты. Один путь:

    DateTime d = DateTime.Now;
    d.Subtract(new TimeSpan(0, 0, 0, 0, d.Millisecond));

можно также вычесть два datetimes

d. Вычтите (DateTime. Теперь);

Это возвратит объект промежутка, который можно использовать для сравнения дней, часов, минут и компонентов секунд для наблюдения различия.

14
задан Luiggi Mendoza 8 April 2015 в 04:14
поделиться

4 ответа

If one is writing a class that is going to have its objects be compared in some way, then one should override the equals and hashCode methods.

Not providing an explicit equals method will result in inheriting the behavior of the equals method from the superclass, and in the case of the superclass being the Object class, then it will be the behavior setforth in the Java API Specification for the Object class.

The general contract for providing an equals method can be found in the documentation for the Object class, specifically, the documentation of the equals and hashCode methods.

16
ответ дан 1 December 2019 в 10:03
поделиться

Only override equals() if it makes sense. But obviously if you override equals() you need to ensure that the hashcode() contract isn't broken, meaning if two objects are equal they must have the same hash code.

When does it make sense? When Object.equals() is insufficient. That method basically comes down to reference identity, meaning two objects are the same object so:

a.equals(b) iff q == b

Numbers are an obvious example when it makes sense because Integer(10) should equal another Intger(10).

Another example could be when you're representing database records. Let's say you have Student records with a unique integer ID, then it might be sufficient implementation of equals to simply compare the ID fields.

5
ответ дан 1 December 2019 в 10:03
поделиться

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the equals() method.You should always override the equals() method if the identity operator is not appropriate for your class.

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.

4
ответ дан 1 December 2019 в 10:03
поделиться

Хотя вы не должны полагаться на IDE, Eclipse предоставляет эту стандартную функциональность, нажав alt + shift + s и выбрав пункты меню equals и hashCode. Также есть опция toString. Эффективная Java Джоша Блоха дает хорошую информацию по этому поводу. Ссылка приведет вас к главе, размещенной в Google Книгах, в которой обсуждается эта тема.

2
ответ дан 1 December 2019 в 10:03
поделиться
Другие вопросы по тегам:

Похожие вопросы: