Comparing Strings using java -
this question has answer here:
- overriding java equals() method quirk 8 answers
i have create equals method return true if politicians' titles same. how compare strings?
this how i've tried write 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, return false. when 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 , don't know why it's not working anymore
public boolean equals(politician a) doesn't override equals method in class java.lang.object.
declare public boolean equals(object a) override method.
public boolean equals(object a) { politician p = (politician) a; return title.equals(p.title); }
btw, legal use p.title inside politician class though title private in politician class. checkout post: access private field of object in same class
Comments
Post a Comment