我检查 2 个对象(数组列表中的一个新对象和一个旧对象)是否匹配。如果匹配,程序将打印“公司已存在!”
,如果不匹配,则将新对象添加到列表中。
问题是,当我尝试两次放置相同的对象(相同的值)时,它显示它已经存在,但当我输入全新的对象(具有不同的值)时,它仍然显示该消息,但将对象添加到数组中列表
if(companyList.size()!=0){
for(i=0;i<companyList.size();i++){
Company oldCom = companyList.get(i);
if(newUab.equals(oldCom)==true){
JOptionPane.showMessageDialog(null, "Company exists already!");
break;
}
else{
companyList.add(newUab);
}
}
}
else{
companyList.add(newUab);
}
我尝试了这个System.out.println(newUab.equals(oldCom));
,它总是给出true
但我不明白为什么当它们不同时,对象被放入数组列表中,而当它们相同时,它不会在这两种情况下打印消息?
我是否错过了什么,或者我花了很长时间查看代码却再也看不到我的错误了?
编辑:我放置这两个类是因为我对什么方法有效缺乏了解(我认为它应该是 UAB 类方法,因为对象属于此类) 公司类别(父级)
public class Company {
public String b;// boss
public String n;// name
public Company(String boss, String name){
b=boss;
n=name;
}
@Override
public int hashCode() {
int hash = 7;
int newHash;
hash = 43 * hash + Objects.hashCode(this.b);
hash = 43 * hash + Objects.hashCode(this.n);
newHash=hash;
return newHash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Company other = (Company) obj;
if (!Objects.equals(this.b, other.b)) {
return false;
}
if (!Objects.equals(this.n, other.n)) {
return false;
}
return true;
}
UAB 类(公司子级):
public class UAB extends Company {
private int w;//workers
public UAB(String boss,String name,int workers){
super(boss,name);
w=workers;
}
@Override
public int hashCode() {
int hash = 3;
hash = 17 * hash + this.w;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UAB other = (UAB) obj;
if (this.w != other.w) {
return false;
}
return true;
}
最佳答案
关于java - 它用 .equals 语句做了不该做的事情 JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23912929/