HashSet的主场迎战的ArrayList [英] HashSet vs. ArrayList
问题描述
所以我有一个自定义类类,将有一个集中的另一个自定义类的学生。因此,这将是这个样子:
公共类类{
私人设置<的Student GT;学生们; //其他方法
}
现在,我将添加和移除许多学生设定的和我的学生也将改变许多学生的私人领域已经在集合的学生。
问题:我应该使用最好什么数据结构实现这个?由于我会改变Student对象的属性集的学生(从而改变了哈希codeS)我应该使用ArrayList呢?
我应该用最好什么数据结构实现这个?由于我会改变Student对象的属性集的学生(从而改变了哈希codeS)我应该使用ArrayList呢?
块引用>如果哈希codeS的元素集合易于改变,那么你不应该使用
HashSet的
。 (如果你这样做,数据结构将打破,并在集合中的元素易于失踪。)但我怀疑,你应该使用
的ArrayList
不是,因为如果散code()
敏感要改变对象,那么等于(对象)
将最有可能是太。这意味着,包含(...)
和类似的方法将无法找到对象。我觉得你应该使用
地图
类型,然后使用学生识别作为重点。(您也可以覆盖
散code
和等于
,这样的平等是指两个物体具有相同的ID。但是,使等于(对象)
无用用于其他用途。)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.
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?
解决方案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?
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.)But I doubt you should be using
ArrayList
either, because ifhashcode()
is sensitive to changes to the object, thenequals(Object)
will most likely be too. And that means thatcontains(...)
and similar methods won't be able to find objects.I think you should be using a
Map
type, and using a "student identifier" as the key.(You could also override
hashcode
andequals
so that equality means that two objects have the same id. But that makesequals(Object)
useless for other purposes.)这篇关于HashSet的主场迎战的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!