【发布时间】:2023-04-01 14:42:01
【问题描述】:
我有一个 ArrayList data 包含 Person 类型的对象,它每 n 秒更新一次,并且具有现有数据的总量。
为了在表中显示这些数据,我使用 clear() 一个 ObservableList 并使用 addAll(data) 来避免 GUI 卡顿。
我想使用 HashSet 作为 Observable 集合,我想知道是否有一种有效的方法可以从 HashSet 更新对象(如果它只是部分相等)。
代码:
class Person {
int id;
String name;
int visits; //this value can be different
@Override
int hashCode() {
//...
}
@Override
boolean equals() {
//...
}
}
class Main {
static void main(String[] args) {
List<Person> data = new ArrayList<>();
data.add(new Person(1, Max, 4);
data.add(new Person(2, Richard, 7);
data.add(new Person(3, Tom, 4);
Set<Person> set = new HashSet<>();
set.addAll(data);
// new Data incoming
// could be the same Person (all 3 variables same)
// could be existing Person but with changed variables (id stays the same)
// could be completely new Person (new id)
}
}
期望的输出:
如果新数据是用现有的 Person 但不同的变量添加的
new Person(1, Max, 50);
该位置的索引应删除 Max 并添加 50 次访问的新 Max(可能在同一位置)
或者最好将变量访问次数更改为 50。
如果所有数据都相同(用 equals() 和 hashCode() 检查):不应添加或删除任何内容
如果 HashSet 中没有新的人(具有新的 id),则应该添加它
如何做到这一点? 我尝试使用 2 个 for 循环(执行耗时)并覆盖哈希集,但我不确定这种方法。
【问题讨论】:
-
使用可以使用名称作为哈希图中的键,并且每次键已经存在时调用该对象的更新方法