我正在研究一个多项式计算器.我的问题是使用equals方法.这是相关代码:
public class Poly{
Term[] terms;
//Constructors-------------------------------------------
public Poly() {}
public Poly(ArrayList<Term> Terms) {
terms = Terms.toArray(new Term[Terms.size()]);
Arrays.sort(terms, new TermComparator());
}
//Methods-------------------------------------------------
public boolean equals(Poly x) {
boolean q=false;
if(this == x){
q=true;
}
return q;
}
//used in constructor to order terms
class TermComparator implements Comparator<Term> {
@Override
public int compare(Term t1, Term t2) {
return t2.getExp() - t1.getExp();
}
}
}
Run Code Online (Sandbox Code Playgroud)
即使两个Poly对象具有相同的值,equals方法也始终返回false.有人可以帮忙吗?
您的Poly类equals方法应如下所示
@Override
public boolean equals(Object obj) {
if (this == obj) //checking both are same instance
return true;
if (obj == null) // checking obj should not be null
return false;
if (getClass() != obj.getClass()) //checking both objects from same class
return false;
Poly other = (Poly) obj;
return Arrays.equals(terms, other.terms); //checking all the array values
}
Run Code Online (Sandbox Code Playgroud)
如果要将Poly对象添加到集合中,则还需要实现哈希代码方法.
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(terms);
return result;
}
Run Code Online (Sandbox Code Playgroud)
请参考
为什么我需要覆盖Java中的equals和hashCode方法?
使用JPA和Hibernate时应该如何实现equals和hashcode
| 归档时间: |
|
| 查看次数: |
608 次 |
| 最近记录: |