I have a class exactly like this:
public class Operator {
private String oper;
private boolean ltr;
private int pc;
//Ignore these methods...
public Operator(String t,int prc,boolean as) {oper=t;pc=-prc;ltr=as;}
public int precedence() {return pc;}
public boolean associativity() {return ltr;}
public String getName() {return oper;}
public int hashCode() {
int hash = 3;
hash = 19 * hash + (this.oper != null ? this.oper.hashCode() : 0);
hash = 19 * hash + (this.ltr ? 1 : 0);
hash = 19 * hash + this.pc;
return hash;
}
public boolean equals(Object o){
if (o instanceof String){
return oper.equals(o);
}
return false;
}
public String toString(){
return oper;
}
}
when I do: System.out.println(new Operator("+",4,true).equals("+")); it prints true, which means that equals method is working.
but when I do this:
Vector oprs = new Vector();
oprs.addElement(new Operator("+",4,true));
int iof = oprs.indexOf("+");
System.out.println(iof);
iof is -1. Manual searching finds it well, and System.out.println(oprs.elementAt(0)); prints +. I thought indexOf uses equals method to find the element (like in Java SE) so why on earth oprs.indexOf isn’t working?
The type of “+” is String. You can’t redefine equality for the String class so your equals method is not reflexive. Check out the Comparator class. It (and the collection classes that use it) might help you.