# Метод equals()

Метод equals() класса Object проверяет, эквивалентны ли два объекта. Поскольку метод equals() реализован в классе Object, он определяет лишь, ссылаются ли переменные на один и тот же объект. В качестве проверки по умолчанию эти действия вполне оправданы: всякий объект эквивалентен самому себе.

Пример

```
public class Student
{
  private int student_id;

  public Student(int student_id)
  {
    this.student_id = student_id;
  }

  public static void main(String[] args)
  {
    Student s1 = new Student(8888);
    Student s2 = new Student(8888);

    if(s1.equals(s2)){
        System.out.println("Они равны!");
    }
    else{
        System.out.println("Они не равны!");
    }
  }
}
```

В представленном выше примере объекты Student созданы в конструкторе с одинаковым student\_id, а метод main выводит на экран: "Они не равны!" Причина состоит в том, что вы не переопределили метод equals. При непереопределенном методе equals виртуальная машина просматривает адреса памяти каждого объекта, сравнивает их и в этом случае возвращает false. Это не то, чего хотим мы. Мы на самом деле хотим сравнить содержимое каждого объекта Student.

Чтобы решить эту проблему мы должны переопределить метод equals в классе Student таким образом.

```
public class Student
{
  private int student_id;

  public Student(int student_id)
  {
    this.student_id = student_id;
  }

  public boolean equals(Object obj)
  {
    if(obj == this){
        return true;
    }

     /* obj ссылается на null */

    if(obj == null){
        return false;
    }

     /* Удостоверимся, что ссылки имеют тот же самый тип */

    if(!(getClass() == obj.getClass())){
        return false;
    }
    else{
      Student tmp = (Student)obj;
      if(tmp.student_id == this.student_id){
        return true;
      }
      else{
        return false;
      }
    }
  }

  public static void main(String[] args)
  {
    Student s1 = new Student(8888);
    Student s2 = new Student(8888);

    if(s1.equals(s2)){
        System.out.println("Они равны!");
    }
    else{
        System.out.println("Они не равны!");
    }
  }
}
```

Задание 1

```
Как будет выглядеть переопределённый метод equals для мобильных телефонов(аппаратов)?
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://comaqa.gitbook.io/java-automation/oop-v-java/metod-equals.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
