HashSet 与 ArrayList [英] HashSet vs. ArrayList

查看:35
本文介绍了HashSet 与 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个自定义类 Class,它将有一组另一个自定义类 Students.所以它看起来像这样:

So I have a custom class Class that will have a set of another custom class Students. So it will look something like this:

public class Class {
    private Set<Student> students;

    // other methods
}

现在,我将向集合学生添加和删除许多学生,并且我还将更改学生集合中已有的学生的许多私有字段.

Now I will be adding and removing many students to the set students and i will also be changing many of the private fields of a student already in the set of students.

问题:我应该使用什么数据结构来最好地实现这一点?由于我将更改 set student 中 Student 对象的属性(从而更改哈希码),我应该改用 ArrayList 吗?

QUESTION: What data structure should I use to best implement this? Since I will be changing the property of the Student objects in set student (thereby changing the hashcodes) should I use an ArrayList instead?

推荐答案

我应该使用什么数据结构来最好地实现这一点?由于我将更改 set student 中 Student 对象的属性(从而更改哈希码),我应该改用 ArrayList 吗?

What data structure should I use to best implement this? Since I will be changing the property of the Student objects in set student (thereby changing the hashcodes) should I use an ArrayList instead?

如果集合元素的哈希码可能会改变,那么您不应该使用 HashSet.(如果这样做,数据结构将中断,并且集合中的元素可能会丢失.)

If the hashcodes for the set elements are liable to change, then you should NOT be using a HashSet. (If you do, the data structure will break, and elements in the set are liable to go missing.)

但我怀疑您是否应该使用 ArrayList,因为如果 hashcode() 对对象的更改敏感,则 equals(Object) 很可能也是.这意味着 contains(...) 和类似的方法将无法找到对象.

But I doubt you should be using ArrayList either, because if hashcode() is sensitive to changes to the object, then equals(Object) will most likely be too. And that means that contains(...) and similar methods won't be able to find objects.

我认为您应该使用 Map 类型,并使用学生标识符"作为键.

I think you should be using a Map type, and using a "student identifier" as the key.

(您也可以覆盖 hashcodeequals 以便相等意味着两个对象具有相同的 id.但这使得 equals(Object) 用于其他目的.)

(You could also override hashcode and equals so that equality means that two objects have the same id. But that makes equals(Object) useless for other purposes.)

这篇关于HashSet 与 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆