您可能忽略了为equals 和hashCode 实现关键的Object 覆盖。
此问题并非特定于 OpenJFX 类 ObservableList。任何执行比较的集合(列表、集合、映射等)都将取决于您为至少equals 和可能的hashCode 编写适当的覆盖。 (提示:总是覆盖两者或都不覆盖,永远不要单独覆盖。)
以下是使用修改后的代码的示例代码。顺便说一句,你错过了一个右括号。此外,如果您遵循 Java 命名约定,生活会更轻松。
为简洁起见,我们使用 Java 16+ 中的新 records 功能。记录是编写类的一种更简洁的方式,其主要目的是透明且不可变地传递数据。您只需要声明每个成员字段的类型和名称。编译器隐式创建构造函数、getter、equals & hashCode 和 toString。最后三个方法默认检查每个成员字段的值。
为简单起见,我们在本地声明了record。您也可以将其声明为嵌套或分离。
package work.basil.example;
import javafx.collections.*;
public class App {
public static void main ( String[] args ) {
System.out.println ( "Hello World!" );
App app = new App ();
app.demo ();
}
private void demo () {
record Person( int id , String firstName , String lastName ) { }
ObservableList < Person > UserMission = FXCollections.observableArrayList ();
Person p1 = new Person ( 1 , "Alice" , "Anderson" );
UserMission.add ( p1 );
if ( UserMission.contains ( new Person ( 1, "Alice" , "Anderson" ) ) ) {
System.out.println ( "true" );
} else {
System.out.println ( "false" );
}
}
}
运行时。
世界你好!
是的
如果使用 Java 的早期版本,或者如果记录不适合您的情况,请编写类似于以下内容的类。注意方法equals & hashCode。
package work.basil.example;
import java.util.Objects;
public final class Person {
private final int id;
private final String firstName;
private final String lastName;
public Person ( int id , String firstName , String lastName ) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int id () { return id; }
public String firstName () { return firstName; }
public String lastName () { return lastName; }
@Override
public boolean equals ( Object obj ) {
if ( obj == this ) return true;
if ( obj == null || obj.getClass () != this.getClass () ) return false;
var that = ( Person ) obj;
return this.id == that.id &&
Objects.equals ( this.firstName , that.firstName ) &&
Objects.equals ( this.lastName , that.lastName );
}
@Override
public int hashCode () {
return Objects.hash ( id , firstName , lastName );
}
@Override
public String toString () {
return "Person[" +
"id=" + id + ", " +
"firstName=" + firstName + ", " +
"lastName=" + lastName + ']';
}
}
覆盖equals/hashCode的问题已经被讨论过很多次了。 Search to learn more.