0

I have a project about car registrations. I have a class named RegNo which implements the comparable interface. It should contain the equals and hashCode functions overridden as I am using this in hashmap. Kindly help me get along with this. The class code is as follows:

package main;

public class RegNo implements Comparable<RegNo> {
    private final String regNo;
    
    public RegNo(String regNo)
    {
        this.regNo = regNo;
    }
    
        
    /*
     * implementing the compareTO method which is defined
     *  in Comparable class as an abstract method
     *  the method returns 0 if both the registration numbers being compared are equal
     *  it returns 1 if the regNo of the object calling this method is lexicographically greater than the parameter
     *  and the method returns a -1, if the regNo of the parameter is greater than the object calling the method
     *  */
    @Override
    public int compareTo(RegNo reg) {
        // TODO Auto-generated method stub
        if(this.regNo == reg.regNo) //both the registration numbers are equal
            return 0;
        else if(this.regNo.compareTo(reg.regNo) > 0)
            return 1;
        else
            return -1;
    }
}
  • 2
    Does [this](https://stackoverflow.com/q/2265503/1712172) question help? – code_mechanic Apr 16 '21 at 02:48
  • 3
    Your ``compareTo()`` method should use either equals() or compareTo() to compare the two strings. == only works to test if the two strings refer to the same object. – NomadMaker Apr 16 '21 at 03:37
  • @Farzana - you need to consider what if compareTo is called with a `null`. – Mr R Apr 16 '21 at 06:44

1 Answers1

-1

Try delegate String's method

        public static class RegNo implements Comparable<RegNo> {
            private final String regNo;

            public RegNo(String regNo)
            {
                this.regNo = regNo;
            }

            @Override
            public int compareTo(RegNo reg) {
                return regNo.compareTo(reg.regNo);
            }

            @Override
            public boolean equals(Object o) {
                if (o == null || getClass() != o.getClass()) return false;

                if (this == o) return true;

                RegNo regNo1 = (RegNo) o;
                return regNo.equals(regNo1.regNo);
            }

            @Override
            public int hashCode() {
                return regNo.hashCode();
            }
        }
ZiWen WEN
  • 1
  • 1