First, you should really type your Comparable
. This way, you have access to the object that you want to compare against without having to cast.
public class PostalCodes implements Comparable<PostalCodes>
Then, when you implement compareTo
, you only need to do it on the city
field.
public int compareTo(PostalCodes other) {
return city.compareTo(other.getLocation());
}
You may have to check for null
on the object other
, or city
from both instances.
There may be other fields that you want to compare against, but from what you're showing us, two PostalCodes
compare based on their city
field. The above is the way to do that.
If you have more fields you need to compare against, you would add them in.
(You would also be better served by making your getter for city
more conventional.)