Search code examples
javaclassmethodsinstance-variables

Comparing two class objects with a method


I have a multitude of objects that are created with multiple instance variables (a string a multiple integers) I have to create a method that will check for equality between the object that executes the method and another object. By that I mean that I would want to see whether all the instance variables are the same for two objects by calling a method. I'm thinking of something like the equals method (string1.equals(string2)), but can I do the same for an object with multiple instance variables which are not all strings?

example:

    //object1
    String name1= keyb.nextLine();
    int age1= keyb.nextInt();
    int monthborn1;

    //object2
    String name2=keyb.nextLine();
    int age2 = keyb.nextInt();
    int monthborn2;

I need to make a method that compare both objects and sees if they are equal or not.

Thank you very much.


Solution

  • Yes, you can create an equals method for your class. For example:

    public final class Person {
        private final String name;
        private final int age;
        private final int birthMonth;
    
        public Person(String name, int age, int birthMonth) {
            this.name = Objects.requireNonNull(name);
            this.age = age;
            this.birthMonth = birthMonth;
        }
    
        @Override
        public boolean equals(Object o) {
            if (o instanceof Person) {
                Person rhs = (Person) o;
                return name.equals(rhs.name)
                        && age == rhs.age
                        && birthMonth == rhs.birthMonth;
            }
            return false;
        }
    
        // Any time you override `equals`, you must make a matching `hashCode`.
        // This implementation of `hashCode` is low-quality, but demonstrates
        // the idea.
        @Override
        public int hashCode() {
            return name.hashCode() ^ age ^ birthMonth;
        }
    }