0

I have to create an equals method that return true if the Politicians' titles are the same. How do I compare the strings?

This is how I've tried to write it so far:

public class Politician implements Priority{
private String name, title;
private int a;
public Politician(String n, String t, int p){
    name=n;
    title=t;
    a=p;
}
public boolean equals(Politician a){
    if(title.equals(a.title))
        return true;
    return false;
}

However, it just always return false. Even when I test:

Priority t4= new Politician("Arnie", "Governor", 4);
    Politician t5= new Politician("Bill", "Governor", 10);
    System.out.println(t5.equals(t4)); 
    System.out.println(t4.equals(t5));

I've written equals() before and I don't know why it's not working anymore

Maria
  • 383
  • 1
  • 5
  • 21
  • 2
    How are you doing `a.title` if the variable is private? You should make a getter to get the value. `public String getTitle(){return this.title;}` And then simply change your `equals` method to do `public boolean equals(Politician a){return this.title.equals(a.getTitile());}` – 3kings Oct 31 '15 at 02:28
  • Change the strings to `public` – Arc676 Oct 31 '15 at 02:28
  • Or, if you need `private` fields, then add a getter method – Jonathan Lam Oct 31 '15 at 02:29
  • 2
    @3kings It's the same class, so it's ok to access private variables. – Ismail Badawi Oct 31 '15 at 03:01

2 Answers2

8

public boolean equals(Politician a) doesn't override the equals method in class java.lang.Object.

Declare as public boolean equals(Object a) to override the method.

public boolean equals(Object a) {
        Politician p = (Politician) a;
        return title.equals(p.title);
    }

Btw, it is completely legal to use p.title inside the Politician class even though title is private in Politician class. Checkout this post: Access private field of another object in same class

Community
  • 1
  • 1
Bon
  • 3,073
  • 5
  • 21
  • 40
1

Try this :

public class Politician extends Priority{

    public String name, title;
    public int a;

    public Politician(String n, String t, int p) {
        name = n;
        title = t;
        a = p;
    }

    public boolean equals(Object o) {
        Politician a = (Politician) o;
        //System.out.println(a.title +" -  "+title);
        if (title.equals(a.title)) {

            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        Priority t4 = new Politician("Arnie", "Governor", 4);
        Politician t5 = new Politician("Bill", "Governor", 10);
        System.out.println(t5.equals(t4));
        System.out.println(t4.equals(t5));
    }
}
Madushan Perera
  • 2,568
  • 2
  • 17
  • 36