知识点来源群里的大佬,说list处理这个的话,根据数据量的增大,时间复杂度就越高,所以建议使用哈希比较。
跟就描述写了个测试代码
public class TestEntity {
public String name;
public String age;
public TestEntity(String name, String age) {
this.age = age;
this.name = name;
}
public boolean equals(Object obj) {//这个比较要和哈希比较的 字段数一致
if (!(obj instanceof TestEntity)) {
return false;
}
TestEntity p = (TestEntity) obj;
return this.name.equals(p.name) && this.age.equals(p.age);
}
public int hashCode() {//哈希比较哪些内容 可以根据自己的需要 加减字段
return this.name.hashCode() + this.age.hashCode();
}
}
public class TestMain {
public static void main(String[] args) {
HashSet h = new HashSet();
h.add(new TestEntity("h1", "10"));
h.add(new TestEntity("h1", "20"));
h.add(new TestEntity("h3", "30"));
h.add(new TestEntity("h4", "40"));
HashSet s = new HashSet();
s.add(new TestEntity("h3", "30"));
s.add(new TestEntity("h4", "40"));
s.add(new TestEntity("s3", "50"));
s.add(new TestEntity("s4", "60"));
HashSet w = new HashSet();
w.add(new TestEntity("h3", "30"));
w.add(new TestEntity("h4", "40"));
w.add(new TestEntity("w3", "50"));
w.add(new TestEntity("w4", "60"));
List<TestEntity> entities = new ArrayList<>();
Iterator t = h.iterator();
while (t.hasNext()) {
TestEntity p = (TestEntity) t.next();
if (s.contains(p) && w.contains(p)) {
entities.add(p);
}
}
for (int i = 0; i < entities.size(); i++) {
TestEntity entity = entities.get(i);
System.out.println("name: " + entity.name + " age: " + entity.age);
}
}
}

输出结果是这个
本文通过一个具体的代码示例,对比了在处理大量数据时,使用哈希集合与列表的时间复杂度差异。实验证明,随着数据量的增长,哈希集合在查找操作上的效率明显优于列表。
4246

被折叠的 条评论
为什么被折叠?



