HashSet vs. ArrayList

2019-01-25 10:19发布

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?

9条回答
forever°为你锁心
2楼-- · 2019-01-25 10:55

It depends. As you are talking about student so must be there is somthing like id or rollno which is unique. If yes then override the hashcode method and implement the hashcode on the basis of their id's. Then there is no effect on the hashcode by changeing any of the other properties of student.

To chose Set or List is totaly depends upon your requirements. Read this link, and it will clarify the difference between Set and list
What is the difference between Set and List?

And if you are using objects in a Set then you can try to override both the hashcode and the equals method so that control of uniqueness is in you hands.

查看更多
劫难
3楼-- · 2019-01-25 10:57

From your requirement, I thought the best structure should be Map. Set actually underlying uses the Map structure inside, and you also need taking care the equals method override for better lookup. And set and arraylist find the target object need take some find algorithm so it's not so efficient as you expected (especially in the very large collection situation). Even map will waste some space, but if your ID is some kind of primitive type, you could consider the primitive type of map implementation in the Trove library.

查看更多
我只想做你的唯一
4楼-- · 2019-01-25 10:59

For a hashed collection such as HashSet, the key should be immutable. Hashset uses hashing internally to decide the bucket to store the object. And also while retrieving the object it will use hash to find the object bucket. If you are changing the object after storing, it may change the hashcode of the object and Set may not be able to retrieve the correct object. If you need to change the object even after adding it to the collection then using a hashed collection is not a good choice. Rather go for Arraylist, but note that with ArrayList you will lose the advantage to retrieve the desired Student quickly, as it could be with a Set.

查看更多
登录 后发表回答