Depends on your data;

HashSet gives you an O(1) contains() method but doesn't preserve order.

ArrayList contains() is O(n) but you can control the order of the entries.

Array if you need to insert anything in between, worst case can be O(n), since you will have to move the data down and make room for the insertion. In Set, you can directly use SortedSet which too has O(n) too but with flexible operations.

I believe Set is more flexible.

Answer from JNL on Stack Overflow
Top answer
1 of 4
24

Depends on your data;

HashSet gives you an O(1) contains() method but doesn't preserve order.

ArrayList contains() is O(n) but you can control the order of the entries.

Array if you need to insert anything in between, worst case can be O(n), since you will have to move the data down and make room for the insertion. In Set, you can directly use SortedSet which too has O(n) too but with flexible operations.

I believe Set is more flexible.

2 of 4
3

The choice greatly depends on what do you want to do with it.

If it is what mentioned in your question:

I have a collection of objects that are guaranteed to be distinct (in particular, indexed by a unique integer ID). I also know exactly how many of them there are

If this is what you need to do, the you need neither of them. There is a size() method in Collection for which you can get the size of it, which mean how many of them there are in the collection.

If what you mean for "collection of object" is not really a collection, and you need to choose a type of collection to store your objects for further processing, then you need to know, for different kind of collections, there are different capabilities and characteristic.

First, I believe to have a fair comparison, you should consider using ArrayList instead Array, for which you don't need to deal with the reallocation.

Then it become the choice of ArrayList vs HashSet, which is quite straight-forward:

Do you need a List or Set? They are for different purpose: Lists provide you indexed access, and iteration is in order of index. While Sets are mainly for you to keep a distinct set of data, and given its nature, you won't have indexed access.

After you made your decision of List or Set to use, then it is a choice of List/Set implementation, normally for Lists, you choose from ArrayList and LinkedList, while for Sets, you choose between HashSet and TreeSet.

All the choice depends on what you would want to do with that collection of data. They performs differently on different action.

For example, an indexed access in ArrayList is O(1), in HashSet (though not meaningful) is O(n), (just for your interest, in LinkedList is O(n), in TreeSet is O(nlogn) )

For adding new element, both ArrayList and HashSet is O(1) operation. Inserting in the middle is O(n) for ArrayList, while it doesn't make sense in HashSet. Both will suffer from reallocation, and both of them need O(n) for the reallocation (HashSet is normally slower in reallocation, because it involve calculation of hash for each element again).

To find if certain element exists in the collection, ArrayList is O(n) and HashSet is O(1).

There are still lots of operations you can do, so it is quite meaningless to discuss for performance without knowing what you want to do.

🌐
DEV Community
dev.to › gabrielbabler › arraylist-vs-hashset-vs-hashmap-the-main-differences-389g
ArrayList vs HashSet vs HashMap - The main differences - DEV Community
October 17, 2022 - Using ArrayList you can have a resizable list, removing or adding as much data as you want. HashSet is an implementation from the Set interface.
Discussions

java - HashSet vs. ArrayList - Stack Overflow
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. More on stackoverflow.com
🌐 stackoverflow.com
Can someone help please explain hashmaps and hashsets in java to me
I'm assuming you understand the concept of a regular Set: you put a bunch of items together, but you ensure that each item is unique. A Set is practical and eay to use, but it has a problem: it's slow. In order to add an item to a set, you first have to check if that item already exists. That means checking through every item in the Set to see if any of them match. If none match, you add the item. If one matches, you reject it. The same issue for taking an item from the Set. You have to check the entire set to find your item. A HashSet solves this problem. It does this by assigning each item a group. For example, if you have a Set of strings, you can group these strings by their first letter. This makes checking the set a lot easier, since you only have to check one group in the Set to check whether an item already exists. A HashSet is called that way, because it uses a hash to determine what group inside the Set it needs to look into. Every object has a hash, which you can find by using the .getHashCode()-method on that object. More on reddit.com
🌐 r/learnprogramming
6
2
July 21, 2019
java - HashSet vs ArrayList
Given a short key a hashmap returns a handle to data in "practically" one step. That "practically" of course costs a great deal more than a simple get.next() iterated access pattern. Use a hashmap when your primary interest is fast random access to keyed data, use an arraylist when sequential access to data is prime. More on reddit.com
🌐 r/learnprogramming
13
3
April 13, 2011
performance - Why ArrayList is faster than HashSet in java? - Stack Overflow
I used to thing that HashSet is a pretty fast data structure implementation because it uses hashes (and is implemented via HashMap in its turn). I was solving some problems and decided to check More on stackoverflow.com
🌐 stackoverflow.com
April 25, 2017
🌐
Java67
java67.com › 2012 › 07 › difference-between-arraylist-hashset-in-java.html
Difference between ArrayList and HashSet in Java? Answer with Example | Java67
3. The differences between ArrayList and HashSet is that ArrayList is an ordered collection and maintains insertion order of elements while HashSet is an unordered collection and doesn't maintain any order.
Top answer
1 of 9
21

When its comes to the behavior of ArrayList and HashSet they are completely different classes.

ArrayList

  • ArrayList Does not validate duplicates.
  • get() is O(1)
  • contains() is O(n) but you have fully control over the order of the entries.

                          get  add  contains next remove(0) iterator.remove
    ArrayList             O(1) O(1) O(n)     O(1) O(1)      O(1)
    
  • Not thread safe and to make it thread safe you have to use Collections.synchronizedList(...)

HashSet

  • HashSet ensures there are no duplicates.
  • Gives you an O(1) contains() method but doesn't preserve order.

                          add      contains next     notes
    HashSet               O(1)     O(1)     O(h/n)   h is the table 
    
  • Not thread safe and to make it thread safe you have to use Collections.synchronizedSet(...)
2 of 9
7

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 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.

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

(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.)

🌐
Medium
rameshfadatare.medium.com › difference-between-arraylist-and-hashset-in-java-942011584c26
Difference between ArrayList and HashSet in Java | by Ramesh Fadatare | Medium
October 29, 2024 - ArrayList uses a dynamic array to store its elements, which means it can grow as needed. Elements are stored in contiguous memory locations. HashSet, on the other hand, uses a hash table to store its elements.
🌐
GeeksforGeeks
geeksforgeeks.org › java › difference-between-arraylist-and-hashset-in-java
Difference between ArrayList and HashSet in Java - GeeksforGeeks
July 11, 2025 - HashSet also does not provide get() method. Null Object: ArrayList not apply any restriction, we can add any number of null value while HashSet allow one null value.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › difference-between-arraylist-and-hashset-in-java
Difference between ArrayList and HashSet in Java
May 5, 2025 - import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class Demo { public static void main(String[] args) { // Creating ArrayList ArrayList<Integer> list = new ArrayList<>(); // Adding values to it list.add(10); list.add(20); list.add(30); list.add(10); // duplicate allowed // Printing ArrayList values System.out.println("The ArrayList values are:"); for (Integer l : list) { System.out.print(l + " "); } System.out.println(); // Creating HashSet Set<Integer> set = new HashSet<>(); // Adding values to it set.add(1); set.add(2); set.add(3); set.add(2); // duplicate ignored // Printing HashSet values System.out.println("The HashSet values are:"); for (Integer s : set) { System.out.print(s + " "); } } }
🌐
Medium
medium.com › @sibinraziya › java-arraylist-vs-hashset-key-differences-and-when-to-use-each-80f2588d49b5
Java ArrayList vs HashSet: Key Differences and When to Use Each | by Sibinraziya | Medium
April 19, 2025 - Java ArrayList vs HashSet: Key Differences and When to Use Each Overview Both ArrayList and HashSet are part of Java's Collections Framework, but they serve different purposes and have distinct …
🌐
Reddit
reddit.com › r/learnprogramming › can someone help please explain hashmaps and hashsets in java to me
r/learnprogramming on Reddit: Can someone help please explain hashmaps and hashsets in java to me
July 21, 2019 -

I still do not understand it at all after a year of doing CS in uni. If possible please explain them both to me in an ELI5 style. Thanks

Top answer
1 of 3
1
I'm assuming you understand the concept of a regular Set: you put a bunch of items together, but you ensure that each item is unique. A Set is practical and eay to use, but it has a problem: it's slow. In order to add an item to a set, you first have to check if that item already exists. That means checking through every item in the Set to see if any of them match. If none match, you add the item. If one matches, you reject it. The same issue for taking an item from the Set. You have to check the entire set to find your item. A HashSet solves this problem. It does this by assigning each item a group. For example, if you have a Set of strings, you can group these strings by their first letter. This makes checking the set a lot easier, since you only have to check one group in the Set to check whether an item already exists. A HashSet is called that way, because it uses a hash to determine what group inside the Set it needs to look into. Every object has a hash, which you can find by using the .getHashCode()-method on that object.
2 of 3
1
Okey, so let's start with a definition of a hash function. So a hash function is such a function that given input value X will return value Y in a predefined and finite range. Sounds a bit complex but here's an example of the simplest hash function: "Take the first letter of a string". So for "apple" hash would be "a". For "banana" it would be "b" For "citrine" it would be "c". For "behemoth" it also would be "b". Range is finite - letters from "a" to "z". Giving you 24 possible outputs. For the same input you always get the same output however from a given output you will not be able to reconstruct the input. That's a primary difference between hashing and encryption actually - hashing is generally a one way process. Now, imagine we are making an array of strings that has 24 spots in it, each starting with a different letter and going alphabetically (so apple, banana, citrus, door etc). Now, we want to check if a given word exists in our array. If you did it the traditional way, you would do something like this: bool isInArray(word) { for w in wordsArray { if (w == word) {return true;} } return false; } This is an O(n) operation. You have to check an entire array to make sure a given word is or isn't in it. However, if we use our hash function (except we replace 'a' with 0, 'b' with 1... 'z' with 23) we could do it like this: bool isInArray(word) { char firstLetter = word[0]; int hashIndex = firstLetter - 97 (// -97 as https://www.asciitable.com/ - a has a numeric value 97, b is 98 and so on) return (word == wordsArray[hashIndex]); } And now we just need O(1) operations, it's constant. It doesn't matter what word you put in, it's always going to take just the first letter of it, turn it into a value from 0 to 23 and this becomes an index inside an array. Now, as you can imagine this kind of hash function is kinda worthless. You can't for instance have multiple words starting with the same letter as they would both generate the exact same hash. We could improve on it a bit - for instance rather than taking just the first letter we could take a sum of all characters (as in a numeric value), first two characters etc. This does lead us to an interesting discovery however - 2 different values can have an identical hash, depending on how you calculate it. We could still use it to make our lookups much faster however. What if we had an... array of arrays of strings! So for instance: array[0] = ['apple', 'annie', 'avocado'] array[1] = ['banana', 'bomb', 'brown'] etc. In this case such a check wouldn't be an O(1) anymore (first lookup for first character would give us an index that leads to a specific section of an array so we might have to check multiple values inside there) but it still would be much faster than checking through an entire 2D array. And this leads us to hashmaps and hashsets. Hashsets are easier to explain - they would represent our first original array of 24 words. You can check if a given word exists in this array in O(1) operations on average. Hashmaps are somewhat more complex and are more similar to example #2 - they first have a key (hash) and a value (of any type). A very simple example on how to use it would be a program that counts how many times a given word has appeared in a novel. You would first create a hashmap where a key is a string and a value is an integer. If a given string exists - you can add 1 to it's value. If it doesn't - you add it to your hashmap and set the value to 1. This is much more efficient than arrays as on average to check if a given word does or does not exist (and find corresponding value you assigned to it) takes just one operation. Rather than having to go through a whole array. Of course, in practice hash functions are not as simple as "first character" in a string and it actually takes a bit of effort and know how to find 2 different values that generate identical hash. Rest of the logic is unchanged however - you want such a mapping that that lets you allocate any input to a specific index in your array (well, not necessarily an array, I am simplifying a bit) so you can look it up much faster than usual.
🌐
Blogger
javahungry.blogspot.com › 2017 › 10 › difference-between-hashset-and-arraylist-in-java-example.html
5 Difference between HashSet and ArrayList in Java with Example | Java Hungry
ArrayList object output :[1. Alive is awesome, 2. Love yourself] HashSet object output :[Alive is awesome, Love yourself] Similarities between HashSet and ArrayList 1. Allows null : Both HashSet and ArrayList allows null. 2. Synchronized : Both HashSet and ArrayList are non synchronized collection class. One needs to avoid using them in multithreading environment. 3. Traversal : Both HashSet and ArrayList can be traversed through iterator in java.
🌐
Coderanch
coderanch.com › t › 411662 › java › performance-ArrayList-HashSet
Overall performance of ArrayList vs. HashSet (Beginning Java forum at Coderanch)
August 29, 2008 - Some operations are faster on an ArrayList and some operations are faster on a HashSet, due to how these datastructures are organized internally. The API documentation gives some information about the performance of different operations. The documentation for ArrayList says: The size, isEmpty, get, set, iterator, and listIterator operations run in constant time.
🌐
Reddit
reddit.com › r/leetcode › array vs. hashset
Array vs. HashSet : r/leetcode
May 27, 2023 - A set is o(1) lookup but order is not maintained. An array is O(n) lookup so it would not be preferable.
🌐
Quora
quora.com › Whats-faster-ArrayList-LinkedList-HashSet-Set-or-array-in-Java-What-are-the-differences
What's faster: ArrayList, LinkedList, HashSet, Set, or array in Java? What are the differences? - Quora
Answer (1 of 2): I am not specialized in Java so this is a rather general Language unrestricted answer. I suppose Set is just an interface while ArrayList, LinkedList, and HashSet, are implementations actually first two of the interface List. In List, you cannot quickly access your element by i...
🌐
Medium
medium.com › @sreeorg1 › differences-between-arraylist-linkedlist-hashmap-and-hashset-in-java-collections-66ad3fdae673
Differences between ArrayList, LinkedList, HashMap, and HashSet in Java Collections? | by Sreeorg | Medium
March 30, 2024 - ArrayList consumes contiguous memory for elements, potentially leading to wasted space if the initial capacity is too high. LinkedList uses more memory per element due to node overhead but can adapt dynamically to memory needs. HashMap’s memory usage depends on the number of elements and load factor, adjusting dynamically. HashSet’s memory usage is similar to HashMap but with constant placeholder values. Core Java Training Institutes in Chennai equips learners with foundational programming concepts and practical skills, fostering a strong understanding of Java development.