我创建了一个应用程序,并为ObservableList
创建模型我希望调用集合.contains()
方法,该方法需要equals()
,但这总是返回false。我只在equals方法中放了一个字段。当我在if语句中使用getter方法进行比较时,它会像我期望的那样返回true。
import java.util.Objects;
import javafx.beans.InvalidationListener;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.image.Image;
public class Client implements ObservableValue {
private final SimpleStringProperty remoteAddress;
private final SimpleStringProperty userName;
private final boolean connected = true;
private final ObservableList<String> logs
= FXCollections.observableArrayList();
private final ObservableList<Image> imageLogs
= FXCollections.observableArrayList();
public Client(String remoteAddress, String userName) {
this.remoteAddress = new SimpleStringProperty(remoteAddress);
this.userName = new SimpleStringProperty(userName);
}
public SimpleStringProperty remoteAddressProperty() {
return remoteAddress;
}
public SimpleStringProperty userNameProperty() {
return userName;
}
public final String getRemoteAddress() {
return remoteAddress.get();
}
public final void setRemoteAddress(String name) {
this.remoteAddress.set(name);
}
public final String getUserName() {
return userName.get();
}
public final void setUserName(String name) {
this.userName.set(name);
}
public ObservableList<String> getLogs() {
return logs;
}
public ObservableList<Image> getImageLogs() {
return imageLogs;
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
return this.remoteAddress == ((Client) obj).remoteAddress;
}
@Override
public int hashCode() {
int hash = 3;
hash = 37 * hash + Objects.hashCode(this.remoteAddress);
return hash;
}
}
答案 0 :(得分:2)
您需要比较属性的实际字符串内容:
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
return this.remoteAddress.get().equals(((Client) obj).remoteAddress.get());
}
@Override
public int hashCode() {
int hash = 3;
hash = 37 * hash + Objects.hashCode(this.remoteAddress.get());
return hash;
}
答案 1 :(得分:-1)
我认为,你不能用“==”比较两个对象,使用equals:
return this.remoteAddress.equals(((Client) obj).remoteAddress);