IdentitySet / IdentityHashSet(使用IdentityHashMap)

时间:2018-01-03 18:20:38

标签: java set javafx-8 observable identity-map

我知道 IdentityHashMap ,但我需要使用“ identitySet ”(使用 等于 - > o1 == o2) )。当我用“extractor”(JavaFX)监听Observable列表时,我将使用一个:

 List<Person> deleteList = new ArrayList<>();
 List<Person> addList = new ArrayList<>();

 ObservableList<Person> list = FXCollections.observableArrayList(Person.extractor());
    list.add(new Person("a",1));
    list.add(new Person("b",2));
    list.add(new Person("c",3));

    list.addListener((ListChangeListener<Person>) observable -> {
        if(observable.next()) {
            if (observable.wasAdded()) {
                addList.addAll(observable.getAddedSubList());
            }
            if (observable.wasUpdated()) {
                deleteList.add(list.get(observable.getFrom()));
            }
            if (observable.wasRemoved()) {
                deleteList.addAll(observable.getRemoved());
            }
        }
    });

人员类:

public class Person {
private final StringProperty s;
private final DoubleProperty d;

//Getters and Setters
// ...

@Override
public int hashCode() {
    int result = s != null ? s.getValue().hashCode() : 0;
    result = 21 * result + (d != null ? Double.hashCode(d.getValue()) : 0);
    return result;
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Person person = (Person) o;
    if (!s.getValue().equals(person.s.getValue())) return false;
    return d.getValue().equals(person.d.getValue());
}


/**
 *Extractor to observe changes in "Property" fields.
 * @return extractor
 */
public static Callback<Person, Observable[]> extractor() {
    return (Person p) -> new Observable[]{p.sProperty(), p.dProperty()};
}

我需要覆盖equals / hashCode来解决我的其他问题。

    Person p = new Person("a",1);
    Set<Object> set = new HashSet<>();
    set.add(p);
    p.setD(9999);
    set.add(p);
    System.out.println(set.size());  // size = 2;

2 个答案:

答案 0 :(得分:4)

thx ,@ BoorheSpider =&gt; 获取设置,其中包装 IdentityHashMap ,使用 Collections.newSetFromMap()

// get IdentytitySet wich wrap IdentityHashMap
Set<Person> set = Collections.newSetFromMap( new IdentityHashMap<>() ) 
//test 
Person p  = new Person("a",1);
Person p2 = new Person("a",1);
set.add(p);
set.add(p2);
p.setD(999999999);
set.add(p);//add Person with changed "d" to 999999999
System.out.println(set.toString());

打印:

  

[Person {s = StringProperty [value:a],d = DoubleProperty [value:   9.99999999E8]},Person {s = StringProperty [value:a],d = DoubleProperty [value:1.0]}]

答案 1 :(得分:2)