Write a Java Program which compares two object | EasyCoding45

Write a Java Program which compares two object.



Here's a simple example with all the pieces combined into a single Java file. This example includes a class MyClass with an equals method, a custom Comparator, and a class implementing Comparable. Note that this is just for illustration, and in a real-world scenario, you might want to organize your code into separate files based on best practices and maintainability.

Program : (Write a Java Program which compares two objects)


import java.util.Comparator;
import java.util.Objects;
class MyClass implements Comparable<MyClass> {
    private int id;
    private String name;
    public MyClass(int id, String name) {
        this.id = id;
        this.name = name;
    }
    
    public int getId() {
        return id;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        MyClass myObject = (MyClass) obj;
        return id == myObject.id && Objects.equals(name, myObject.name);
    }
    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
    @Override
    public int compareTo(MyClass other) {
        return Integer.compare(this.id, other.id);
    }
}
class MyComparator implements Comparator<MyClass> {
    @Override
    public int compare(MyClass obj1, MyClass obj2) {
        return Integer.compare(obj1.getId(), obj2.getId());
    }
}
public class Main {
    public static void main(String[] args) {
        MyClass obj1 = new MyClass(1, "Object1");
        MyClass obj2 = new MyClass(2, "Object2");
//Using Equals Method
if(obj1.equals(obj2)){
System.out.println("Objects are equal " );
}else{
System.out.println("Objects are not equal " );
}

// Using Comparable
int result = obj1.compareTo(obj2);
if(result > 0){
System.out.println("Objects are equal " );
}else{
System.out.println("Objects are not equal " );
}
//Using Comparator
        MyComparator comparator = new MyComparator();
int res = comparator.compare(obj1, obj2);
if(res >0 ){
System.out.println("Objects are equal " );
}else{
System.out.println("Objects are not equal ");
}
    }
}


Note: Remember that in a real-world scenario, you would likely organize your code into separate files and follow proper class and package naming conventions.

Output :

https://easycoding45.blogspot.com/2023/11/write-java-program-which-compares-two.html


Comments